Why does while (true) skip cin when it received invalid input?(为什么 while (true) 在收到无效输入时会跳过 cin?)
问题描述
这个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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 while (true) 在收到无效输入时会跳过 cin?


- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01