问题
This while-loop does not wait for input from cin after receiving wrong input (non-integer). Does cin somehow stay in a false state?
while (true) {
int x {0};
cout << "> ";
cin >> x;
cout << "= " << x << endl;
}
I would expect this while-loop to wait for input everytime around, but that no longer happens when it receives wrong input.
回答1:
Once cin
fails, it stays in an invalid state until it's cleared.
clear() without arguments can be used to unset the failbit after unexpected input
Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.
As @Peter points out, you also have to clear the buffer.
Your example would be like this:
while (true) {
int x{0};
cout << "> ";
if (!cin) {
// unset failbit
cin.clear();
// clear the buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cin >> x;
cout << "= " << x << endl;
}
来源:https://stackoverflow.com/questions/56303342/why-does-while-true-skip-cin-when-it-received-invalid-input