即使我调用ignore()和clear(),std :: cin也会循环 [英] std::cin loops even if I call ignore() and clear()

查看:66
本文介绍了即使我调用ignore()和clear(),std :: cin也会循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个输入检查循环,以便它不断询问用户有效的(整数)输入,但似乎陷入了无限循环。

I'm trying to setup an input checking loop so it continuously ask the user for a valid (integer) input, but it seems to get trapped in an infinite loop.

我一直在寻找解决方案,并尝试 ignore() clear(),但仍然没有不要停止。

I've searched for solutions and tried to ignore() and clear(), but it still doesn't stop.

请问我在哪里我错了吗?

Could you please correct me where I'm wrong here?

int num;
cin >> num;
while (cin.fail()) {
  cin.ignore();
  cin.clear();
  cout << "Enter valid number: " << endl;
  cin >> num;
}


推荐答案

当流在错误状态,

  cin.ignore();

不执行任何操作。您需要先调用 cin.clear(),然后再调用 cin.ignore()

does not do anything. You need to call cin.clear() first before calling cin.ignore().

此外, cin.ignore()只会忽略一个字符。要忽略一行输入,请使用:

Also, cin.ignore() will ignore just one character. To ignore a line of input, use:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

添加

#include <limits>

能够使用 std :: numeric_limits

固定的代码块如下所示:

The fixed up block of code will look something like:

int num;
while ( !(cin >> num) ) {
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   cout << "Enter valid number: " << endl;
}

这篇关于即使我调用ignore()和clear(),std :: cin也会循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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