cin >> integer and while loop

风格不统一 提交于 2019-12-08 06:57:02

问题


With below code,

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

回答1:


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.

See below for an example:

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

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.




回答2:


Well, this doesn't answer the why, but it does stop the haywiring: system("pause")

void main()
{
    int n{ 0 };

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

        system("pause");
    }

}


来源:https://stackoverflow.com/questions/28623658/cin-integer-and-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!