我目前正在处理一段相当基本的代码。我正在尝试检查用户的输入,以便如果它不是所请求的数字,则会弹出错误消息并请求新的输入。我正在使用一个while循环,当keep命令被命中时应该被重置,但是如果有一个无效的输入,它总是会陷入无限循环,重复错误消息。任何帮助将不胜感激,谢谢!
while (tester != 1){
cout << "Enter your answer: ";
cin >> userInput;
if (cin.fail()){ //check if user input is valid
cout << "Error: that is not a valid integer.\n";
continue; //continue skips to top of loop if user input is invalid, allowing another attempt
} else{
tester = 1; //Tester variable allows loop to end when good value input
}
}
答案 0 :(得分:3)
失败后需要清除输入缓冲区。
如果cin >> something
失败,它将不会消耗&#34;错误&#34;来自输入流的数据,下次返回获取更多数据时,它将读取相同的错误数据。
它会继续这样做,直到奶牛回家,正如奶奶常说的那样 - 不要问我这意味着什么,我很确定她没有#&# 39;花很多时间清醒: - )
您可以使用以下内容消费到行尾:
#include <limits>
:
std::cin.clear();
std::cin.ignore(
std::numeric_limits<std::streamsize>::max(),
'\n');
这是一个完整的程序,展示了它的实际效果:
#include <iostream>
#include <limits>
int main() {
int userInput, tester = 0;
while (tester != 1){
std::cout << "Enter your answer: ";
std::cin >> userInput;
if (std::cin.fail()) {
std::cout << "Not a valid integer.\n";
std::cin.clear();
std::cin.ignore(
std::numeric_limits<std::streamsize>::max(),
'\n');
continue;
} else {
tester = 1;
}
}
return 0;
}
注意特别是使用
std::numeric_limits<std::streamsize>::max()
作为长度,这意味着强制执行 no 限制。很多人会在这种情况下使用INT_MAX
,但这不同样的事情。
在实践中它不太重要,因为INT_MAX
是一个非常大的数字,你可能会在忽略那么多字符之前遇到行尾,但它最好使用保证行为的正确价值。
答案 1 :(得分:1)
您需要清除失败的标志,通常还需要跳过下一个换行符。
通常情况如下:
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');