重置cin流状态C ++ [英] Resetting cin stream state C++

查看:131
本文介绍了重置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:\n";
    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(), '\n')

上面的操作是清除输入流中任何仍留在那里的字符.否则,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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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