2

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

2 Answers2

5

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.

DavidO
  • 13,812
  • 3
  • 38
  • 66
-1

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

}
user97662
  • 942
  • 1
  • 10
  • 29