C ++,得到一个无限循环 [英] C++, getting a infinite loop
问题描述
我尝试使用开关做一个简单的菜单。我还想做一个检查,如果用户做了一个有效的输入(只有int从1到4)。输入-4或44对此检查正常工作。但如果我输入像w这样的东西给我一个无限循环。
我猜我需要另一个if / else与if(!cin)blabla否则继续开关。
但是我不知道我怎么做,else是开始切换。
i try to do a simple menu using switch. I also want to do a check if the user made a valid input (Only int from 1 to 4). Entering -4 or 44 is working fine with this check. But if i enter something like "w" it gives me a infinite loop. I'm guessing i need another if / else with if (!cin) blabla else go ahead with switch. But i'm not sure how i do that the else is starting the switch.
int menu() {
int enter;
bool exit = false;
do {
cout << "Wie soll angefangen werden: " << endl; //Enter your choice
cout << "1 - Spiel starten" << endl; // do game();
cout << "2 - Highscore " << endl; //do score();
cout << "3 - Quiz starten " << endl; //do quiz();
cout << "4 - Ende " << endl; //end the programm
cin >> enter;
switch (enter) {
case 1:
game();
break;
case 2:
score();
break;
case 3:
showQuizDialog();
break;
case 4:
exit = true;
break;
default:
cout << "Keine gültige Eingabe, nochmal: " << endl; //invalid input, again
void flushCin();
} //end of switch
} while (exit == false);
}//end of menu();
推荐答案
这是因为输入正在尝试获取一个整数。当输入不是一个整数,输入留在缓冲区,所以下一次在循环中相同的输入仍然存在。
It's because the input is trying to get an integer. When the input is not an integer, the input is left in the buffer, so next time around in the loop the same input is still there.
此外,你不是在默认情况下,调用 flushCin
函数,您将声明。您可能要删除 void
关键字。我想它做正确的事情吗? (即调用 std :: cin.ignore()
和 std :: cin :: clear()
。)
Also, you are not calling the flushCin
function in the default case, you are declaring it. You might want to remove the void
keyword. I guess it does the correct thing? (I.e. calling std::cin.ignore()
and std::cin::clear()
.)
这篇关于C ++,得到一个无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!