我尝试使用 switch 做一个简单的菜单.我还想检查用户是否进行了有效输入(仅限 1 到 4 的整数).在此检查中输入 -4 或 44 可以正常工作.但是如果我输入类似w"的东西,它会给我一个无限循环.我猜我需要另一个 if/else with 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++,得到一个无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!