一直致力于一个简单的学校项目,但我遇到了一个小问题,涉及通过使用 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 消息,从而跳过对新输入的请求,就会出现问题。我假设非整数总是为 while 循环返回 true,但程序仍应要求用户输入,对吗?
cin.fail 是最近添加的,可能不是必需的,因为它没有解决问题,尽管我将代码保持原样。
最佳答案
如果流中有错误,则将值设置为 0
。所以循环再次运行......错误仍然存在于流中。重复。
您需要清除错误标志。
cin.clear();
然后提取足够多的“坏”数据以获得好的部分,否则您将回到起点。
关于c++ - 虽然循环在输入方面表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44975153/