一直在研究一个简单的学校项目,但我在使用while循环验证用户输入方面遇到了一个小问题 . 以下代码用于执行此操作:
cout << "How much woud you like to bet?[100, 300, 500]" << endl;
cin >> int_input;
if (cin.fail()){
int_input = 0;
}
//Validate check
while(int_input!=100 && int_input!=300 && int_input!=500){
cout << "Please enter a valid bet [100, 300, 500]" << endl;
cin >> int_input;
if (cin.fail()){
int_input = 0;
}
}
当输入非整数并且循环最终反复吐出cout msg时,会出现问题,跳过对新输入的请求 . 我假设一个非整数总是为while循环返回true,但程序仍应该询问用户输入,对吧?
cin.fail是最近添加的,可能没有必要,因为它没有解决问题,尽管我保留了代码 .
1 回答
如果流上有错误,则将值设置为
0
. 所以循环再次运行......错误仍然在流上 . 重复 .您需要清除错误标志 .
然后提取足够的“坏”数据以获得好的部分,或者你只是回到你开始的地方 .