C++, getting a infinite loop(C++,得到一个无限循环)
问题描述
我尝试使用 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++,得到一个无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++,得到一个无限循环
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
