0

Why do I get an infinite loop when I press a letter? How do I prevent my code from going into an infinite loop when error checking?

#include <iostream>
using namespace std;

int main()
{
    int number;
    cout << "Enter a number in the range 1-100: ";
    cin >> number;

    while (number > 1 || number < 100)
    {
        cout << "ERROR: Enter a value in the range 1-100: ";
        cin >> number;

    }
    return 0;
}
Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39
  • I'm to lazy to find a good duplicate (there are quite a few here on stackoverflow.com, and even more out on the wider Internet) ,but the gist of the problem is that when the input operator can't parse the input as a number, it leaves the input in the buffer, it doesn't remove anything. So each time in the loop it will read the same input over and over again. Read about [the `ignore` function](http://en.cppreference.com/w/cpp/io/basic_istream/ignore) to help you. – Some programmer dude Sep 30 '16 at 21:59
  • Think about what the condition in the while statement is doing. – 1201ProgramAlarm Sep 30 '16 at 21:59
  • Also note that if you are using an older compiler or building in pre-C++11 mode, then you will have *undefined behavior* because `number` will not be modified on illegal input. And since it's not initialize then it will have an *indeterminate* value and the comparison in the loop will then give you the UB. – Some programmer dude Sep 30 '16 at 22:03
  • @JoachimPileborg Thanks! – Jesus Hilario Hernandez Oct 04 '16 at 00:52
  • @1201ProgramAlarm Thanks! – Jesus Hilario Hernandez Oct 04 '16 at 00:53

2 Answers2

1

Because std::cin is type safe, it knows that a letter is not a valid input for "int number". It raises an error flag in std::cin and any subsequent operation will fail and return immediately.

You'll need to check the error state and clear any error flag(s) before you can proceed.

See existing post Why do I get an infinite loop if I enter a letter rather than a number?

Community
  • 1
  • 1
Tanguy Fautré
  • 276
  • 2
  • 3
0

Thanks a lot y'all. I ended up going with this one.

while (!(cin >> number)) 
{ 
   cout << "ERROR: Enter a value in the range 1-100: "; 

   //to clear input stream
   cin.clear();   

   //to discard previous input
   cin.ignore(1200, '\n'); 

   cin >> number; 
}