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
  • In this code, it would look more "readable," instead use int n = 0; Commented Feb 20, 2015 at 7:33
  • Possible duplicate of stackoverflow.com/q/18400620/716443 Commented Feb 20, 2015 at 7:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.