Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
Solution 1:
This is how basic_istream
works. In your case when cin >> num1
gets wrong input - failbit
is set and cin
is not cleared. So next time it will be the same wrong input. To handle this correctly you can add check for correct input and clear&ignore cin
in case of wrong input. For example:
#include<limits>
//user enters a number
cout << "\nPlease enter a positive number and press Enter: \n";
do {
while(!(cin >> num1)) {
cout << "Incorrect input. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if(num1 < 0) cout << "The number you entered is negative. Please enter a positive number to continue.\n";
} while(num1 < 0);
Solution 2:
When you enter a letter, the error state of cin
is set and there won't be any further input possible before you call cin.clear()
. In consequence, the statement cin >> num1
will not change the value of num1
and you loop forever.
Try this:
while (num1 < 0)
{
cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
cin.clear();
cin >> num1;
}
EDIT:
Thanks to Lightness for pointing this out. You should initialize num1
too:
int num1=-1, num2, total;