Simple program, stopping invalid character infinite loop
Hi everyone,
I've been super busy over the last couple of months and not had a chance to carry on with the jumping into c++ pdf. However, now I'm back and ready, and stuck, already!
Here is my program, I thought I'd refresh my memory on how loops work:
Code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int userSelection;
string file = "File";
string edit = "Edit";
string view = "View";
string navigate = "Navigate";
cout << "1 - " << file << "\n";
cout << "2 - " << edit << "\n";
cout << "3 - " << view << "\n";
cout << "4 - " << navigate << "\n\n";
cout << "Please select a number from the list: ";
cin >> userSelection;
while ( userSelection < 1 || userSelection > 4 )
{
cout << "Please try again: ";
cin >> userSelection;
}
if ( userSelection == 1 )
{
cout << "You chose " << file;
}
else if ( userSelection == 2 )
{
cout << "You chose " << edit;
}
else if ( userSelection == 3 )
{
cout << "You chose " << view;
}
else
{
cout << "You chose " << navigate;
}
return 0;
}
So it all works ok, entering any number other than 1,2,3 or 4 results in a prompt to "Please try again:".
However, if entering anything other than a number, i.e. a letter, t, r, a, whatever, the cin fails and goes into an infinite loop.
I've been reading about this happening in other people's programs but haven't been able to apply any solution to my own. Looking for some kind of 'not a number' function or something. If the program only allows 1,2,3 or 4 in order to continue, I would have logically thought any other input would be bad, hence show the prompt. However, I don't understand how c++ works so my own logic probably goes out the window!
Any help is much appreciated, thanks.
Sam.