cin >> 整数和 while 循环

cin >> integer and while loop

使用下面的代码,

如果我输入一个字母或一个很长的数字,while 循环就会出错,这是为什么?

void main()
{
    int n{ 0 };

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

好吧,这并没有回答为什么,但它确实阻止了混乱:system("pause")

void main()
{
    int n{ 0 };

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

        system("pause");
    }

}

问题是 operator>> 期望从输入流中提取一个整数,但那里还有其他东西(用户键入的非整数)。这会在输入流上设置一个错误状态。在这种状态下,cin >> ... 构造不再阻塞输入,因为流中已经有一些东西(不是整数),所以你会看到你的循环失控了。

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

示例如下:

#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;
}

"really big number" 也导致这种情况的原因是一个非常大的数字(超过 int 的数字限制的数字)也是 not 一个 int,因此如果您尝试将值读入 int,也不会从输入流中读取。它可能看起来像一个整数,但如果它超出 int 类型的范围,operator>> 不会尝试将其压缩到 int 变量中。错误状态被设置,循环变得混乱。同样,解决方案是检测错误状态,清除错误标志,清空输入缓冲区,如果需要,再次提示。