问题是:
cin >> input;
当您尝试读取非数值时,将导致设置坏位。在那之后,任何使用 的尝试operator>>
都会被忽略。
所以纠正这个问题的方法是测试流是否处于良好状态,如果不是,则重置状态标志并再次尝试读取。但请注意,错误的输入(导致问题的)仍在输入上,因此您需要确保也将其丢弃。
if (cin >> input)
{
// It worked (input is now in a good state)
}
else
{
// input is in a bad state.
// So first clear the state.
cin.clear();
// Now you must get rid of the bad input.
// Personally I would just ignore the rest of the line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// now that you have reset the stream you can go back and try and read again.
}
为了防止它被卡住(这是由设置的坏位引起的)读入字符串,然后使用字符串流来解析用户输入。我也更喜欢这种方法(用于用户交互输入),因为它允许更轻松地组合不同的阅读风格(即组合operator>>
并且std::getline()
您可以在字符串流上使用它们)。
#include <iostream>
#include <sstream>
#include <string>
// using namespace std;
// Try to stop using this.
// For anything other than a toy program it becomes a problem.
int main(int argc, char *argv[])
{
int input;
std::string line;
while(std::getline(std::cin, line)) // read a line at a time for parsing.
{
std::stringstream linestream(line);
if (!(linestream >> input))
{
// input was not a number
// Error message and try again
continue;
}
if ((input < 1) || (input > 3))
{
// Error out of range
// Message and try again
continue;
}
char errorTest;
if (linestream >> errorTest)
{
// There was extra stuff on the same line.
// ie sobody typed 2x<enter>
// Error Message;
continue;
}
// it worked perfectly.
// The value is now in input.
// So break out of the loop.
break;
}
}