我有一个简单的C++菜单,带有可选择的菜单选项。如果用户输入除有效int
之外的任何内容,如char
或double
,程序将进入无限循环。我的代码如下。如果用户输入无效整数,C++菜单陷入无限
#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;
}
为什么无效响应导致无限循环,怎么能防止?
你想检查流的有效性,比如'if(!cin){/ * handle error * /}'。另请参阅[为什么iostream :: eof在循环条件内被认为是错误的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。 – jaggedSpire