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?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
