问题
New to c++ - trying to check for format of input. Have tried everything, at wit's end. Any help would be appreciated. I've broken down my problem to this basic case:
while(1) {
cin >> x;
cout << "asked!" << endl;
cin.ignore(1000, 'n');
}
will result in infinite loop of "asked!" after the first invalid input (entering not int for x). I want to handle incorrect input. The following will not work:
do {
cin.clear();
cin >> x >> y;
if (cin.fail())
{
cout << "Invalid input." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (cin.fail());
回答1:
You should use std::cin.clear()
immediately before std::cin.ignore()
to clear the stream's error state, otherwise all future cin
operations will exit/fail. You can also test the success of std::cin
operations more directly...
do {
if (std::cin >> x >> y) break;
std::cout << "Invalid input, please try again...\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (true);
回答2:
the following worked:
do {
if (cin >> customers >> chairs)
break;
if (cin.fail())
{
cout << "Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (true);
thanks to Tony D
来源:https://stackoverflow.com/questions/28533483/checking-cin-input-clearing-input-buffer