cin>>整数和while循环 [英] cin >> integer and while loop

查看:189
本文介绍了cin>>整数和while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,

如果我输入字母或非常长的数字,则while循环会陷入麻烦,为什么呢?

if I enter a letter or a really long number, the while loop will go haywire, why is that?

void main()
{
    int n{ 0 };

    while (true)
    {
        cout << "Enter a number: ";
        cin >> n;
        cout << n << endl;
    }
}


推荐答案

问题是 operator>> 期望从输入流中提取一个整数,但是那里还有其他内容(用户键入的非整数)。这将在输入流上设置错误状态。在这种状态下, cin>> ... 构造不再阻止输入,因为流中已经有东西(不是整数),所以您会发现循环陷入困境。

The problem is that operator>> is expecting to draw an integer off of the input stream, but there is something else sitting there (the non-integer that the user typed). This sets an error state on the input stream. In this state, the cin >> ... construct no longer blocks for input because there's already something (not an integer) in the stream, so you see your loop go haywire.

需要发生的是,当输入了不正确的输入时,必须检测到错误状态,必须清除输入流,并且必须清除错误状态。此时,可能会输入新的(希望正确的)输入。

What needs to happen is that when improper input is entered, the error state must be detected, the input stream must be flushed, and the error state must be cleared. At that point, new (hopefully correct) input may be entered.

请参见以下示例:

#include <iostream>
#include <limits>

using namespace std;

int main () {
  int x = 0;
  while(true) {
    cout << "Enter a number: ";
    if( ! (cin >> x) ) {
      cin.clear();
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      cerr << "Invalid input. Try again.\n";
    }
    else {
      cout << "\t..." << x << "...\n";
    }
  }
  return 0;
}

数量很大也会导致这种情况的原因是很大的数字(超过 int 的数字限制)也 not int ,因此,如果您尝试将值读入 int ,也不会从输入流中读取该值。它可能看起来像整数,但是如果 int 类型超出范围,则 operator>> 是'尝试将其压缩为 int 变量。错误状态被设置,循环陷入困境。同样,解决方案是检测错误状态,清除错误标志,清空输入缓冲区,然后根据需要再次提示。

The reason that a "really big number" also causes this condition is that a really big number (one that exceeds the numeric limits of an int) is also not an int, and therefore will also not be read off the input stream if you are trying to read the value into an int. It may look like an integer, but if it's out of bounds for an int type, operator>> isn't going to try to squeeze it into an int variable. The error state gets set, loop goes haywire. Again, the solution is to detect error state, clear the error flag, empty the input buffer, and if you wish, prompt again.

这篇关于cin&gt;&gt;整数和while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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