问题描述
这个while循环在接收到错误的输入(非整数)后不等待来自cin的输入.cin 是否以某种方式保持在虚假状态?
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;
}
我希望这个 while 循环每次都等待输入,但是当它接收到错误的输入时不再发生这种情况.
I would expect this while-loop to wait for input everytime around, but that no longer happens when it receives wrong input.
推荐答案
一旦 cin
失败,它会一直处于无效状态,直到被清除.
Once cin
fails, it stays in an invalid state until it's cleared.
clear() 不带参数可用于取消设置意外输入后的故障位
clear() without arguments can be used to unset the failbit after unexpected input
通过为它们分配值来设置流错误状态标志状态.默认情况下,分配具有效果的 std::ios_base::goodbit清除所有错误状态标志.
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.
正如 @Peter 指出的那样,您还必须清除缓冲区.
As @Peter points out, you also have to clear the buffer.
你的例子是这样的:
while (true) {
int x{0};
cout << "> ";
if (!cin) {
// unset failbit
cin.clear();
// clear the buffer
cin.ignore(numeric_limits<streamsize>::max(), '
');
}
cin >> x;
cout << "= " << x << endl;
}
这篇关于为什么 while (true) 在收到无效输入时会跳过 cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!