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?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01