复制cin流状态c ++ [英] Resseting cin stream state c++

查看:125
本文介绍了复制cin流状态c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在输入非整数值(例如dsdfgsdg)后,cin.fail )返回true,正如预期和while循环体开始执行。



这里我使用cin.clear()重置cin的错误标志。和cin.fail()返回false,如预期。



但下一次调用cin不起作用,并设置错误标志。



有什么想法吗?

 #include< iostream> 
using namespace std;

int main(){
int a;
cin>>一个;

while(cin.fail()){
cout< 数据不正确。输入新整数:\\\
;
cin.clear();
cin>>一个;
}
}


解决方案

cin.clear(),您可以这样做:

  #include< ; iostream> // std :: riversize,std :: cin 
#include< limits> // std :: numeric_limits
....
std :: cin.ignore(std :: numeric_limits< std :: streamsize> :: max(),'\\\
')

上面的操作是清除仍然留在那里的任何字符的输入流。否则,cin将继续尝试读取相同的字符和失败


Here Im trying to get an integer from user, looping while the input is correct.

After entering non integer value (e.g "dsdfgsdg") cin.fail() returns true, as expected and while loop body starts executing.

Here I reset error flags of cin, using cin.clear(); and cin.fail() returns false, as expected.

But next call to cin doesn't work and sets error flags back on.

Any ideas?

#include<iostream>
using namespace std;

int main() {
  int a;
  cin >> a;

  while (cin.fail()) {
    cout << "Incorrect data. Enter new integer:\n";
    cin.clear();
    cin >> a;
  }
} 

解决方案

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(), '\n')

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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆