C++;如果用户输入无效整数,则菜单卡在无穷大中 我有一个简单的C++菜单,菜单可以选择。如果用户键入的不是有效的int,例如char或double,程序将进入无限循环。我的代码如下 #include <iostream> using namespace std; int main() { int selection; do { cout << "1) Update inventory" << endl; cout << "2) Sell items" << endl; cout << "3) List inventory" << endl; cout << "4) Quit" << endl; cout << "Please select an option: "; cin >> selection; } while (selection != 4); return 0; } #包括 使用名称空间std; int main() { int选择; 做{ 手术前cout

C++;如果用户输入无效整数,则菜单卡在无穷大中 我有一个简单的C++菜单,菜单可以选择。如果用户键入的不是有效的int,例如char或double,程序将进入无限循环。我的代码如下 #include <iostream> using namespace std; int main() { int selection; do { cout << "1) Update inventory" << endl; cout << "2) Sell items" << endl; cout << "3) List inventory" << endl; cout << "4) Quit" << endl; cout << "Please select an option: "; cin >> selection; } while (selection != 4); return 0; } #包括 使用名称空间std; int main() { int选择; 做{ 手术前cout,c++,menu,user-input,infinite-loop,C++,Menu,User Input,Infinite Loop,cin >> selection; 放置以下两行: cin.clear (); cin.ignore (); 这将清除缓冲区并允许进行输入。这不是他要求的。他要求的是无效输入,例如输入的是字符而不是数字。这将解决问题。但是@jaggedSpire是正确的。您希望检查流的有效性,如if(!cin){/*handle error*/}。另请参见。

cin >> selection;
放置以下两行:

cin.clear ();
cin.ignore ();

这将清除缓冲区并允许进行输入。

这不是他要求的。他要求的是无效输入,例如输入的是字符而不是数字。这将解决问题。但是@jaggedSpire是正确的。您希望检查流的有效性,如
if(!cin){/*handle error*/}
。另请参见。