【发布时间】:2015-01-11 12:01:56
【问题描述】:
我目前正在这里编写一段相当基本的代码。我正在尝试检查用户的输入,以便如果它不是请求的数字,则会弹出错误消息并请求新的输入。我正在使用一个 while 循环,当遇到 continue 语句时应该重置它,但是如果输入无效,它总是会陷入无限循环,重复错误消息。任何帮助将不胜感激,谢谢!
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
}
}
【问题讨论】:
标签: c++ loops while-loop infinite-loop continue