How come if I enter a letter input my program gets stuck in its while loop?

前端 未结 2 1578
予麋鹿
予麋鹿 2021-01-07 05:03

Sorry if I fail to be clear enough or make any mistakes, this is my first time posting.

My code runs without errors when complied but the first while loop (in in

2条回答
  •  梦毁少年i
    2021-01-07 05:03

    Ad Ed Heal mentioned, the issue here is cin's failbit. When you do cin >> choice, and the user types "a", then the conversion to int fails. This sets cin's failbit, making all future reads from it fail until the failbit is cleared. So the next time you reach cin >> choice, the user won't even get to type anything.

    You can use cin.clear() to restore to working order.

    To do this a bit more robustly, you could do something like

    while(true)
    {
        cout >> "Enter choice [1-4]: ";
        if(!(cin >> choice))
        {
            cout << "Input must be an integer.\n";
            cin.clear();
            continue;
        }
        do_stuff_with_choice();
     }    
    

提交回复
热议问题