为什么while(true)收到无效输入时会跳过cin? [英] Why does while (true) skip cin when it received invalid input?

查看:101
本文介绍了为什么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(), '\n');
  }
  cin >> x;
  cout << "= " << x << endl;
}

这篇关于为什么while(true)收到无效输入时会跳过cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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