Jesus Hilario Hernandez Jesus Hilario Hernandez - 2 months ago 8
C++ Question

Why do I get an infinite loop when I press a letter? How do I change for error checking?

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

Answer

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