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