Resetting cin stream state C++(重置cin流状态C++)
问题描述
这里我试图从用户那里获取一个整数,在输入正确时循环.
Here Im trying to get an integer from user, looping while the input is correct.
输入非整数值(例如dsdfgsdg")后,cin.fail() 返回 true,正如预期的那样,while 循环体开始执行.
After entering non integer value (e.g "dsdfgsdg") cin.fail() returns true, as expected and while loop body starts executing.
这里我使用cin.clear()来重置cin的错误标志;正如预期的那样,cin.fail() 返回 false.
Here I reset error flags of cin, using cin.clear(); and cin.fail() returns false, as expected.
但是下一次调用 cin 不起作用并重新设置错误标志.
But next call to cin doesn't work and sets error flags back on.
有什么想法吗?
#include<iostream>
using namespace std;
int main() {
int a;
cin >> a;
while (cin.fail()) {
cout << "Incorrect data. Enter new integer:
";
cin.clear();
cin >> a;
}
}
推荐答案
在 cin.clear() 之后,你这样做:
After cin.clear(), you do this:
#include <iostream> //std::streamsize, std::cin
#include <limits> //std::numeric_limits
....
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '
')
上面的作用是清除输入流中仍留在那里的任何字符.否则 cin 将继续尝试读取相同的字符并失败
What the above does is that it clears the input stream of any characters that are still left there. Otherwise cin will continue trying to read the same characters and failing
这篇关于重置cin流状态C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重置cin流状态C++
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
