I have a small loop that gets the user input, as well as acts as input validation to make sure he or she doesn't enter a value that is not within the specified range.
The user is supposed to enter a month number. E.g. if he or she chooses February, then enter 2, or December, 12.
It works correctly if they type a number that is not in the range, but goes into an infinite loop if, say, they type a string such as "month".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
// Variable Declaration(s)/Initialization(s)
int month=0;
// Get input
cout<<"Enter a month";
cin>>month;
while ((month<1)||(month>12))
{
cout<<"Error: That is not a valid month."
cout<<"\nEnter the month. (E.g. January would be 1, September \
would be 9, etc.)\n";
cin>>month;
}
}
How could I go about revising this? Any help would be greatly appreciated.
int main()
{
// Variable Declaration(s)/Initialization(s)
int month=0;
// Get input
cout<<"Enter a month";
cin>>month;
// add !cin to loop condition:
while (!cin || (month<1)||(month>12))
{
cout<<"Error: That is not a valid month."
cout<<"\nEnter the month. (E.g. January would be 1, September would be 9, etc.)\n";
cin.clear(); // clear error state.
cin.ignore(1000, '\n'); // remove offending data from stream.
cin>>month;
}
}