Becasue your program does not check the result of cin >> num;
. Since cin >> num;
(where num
is an integer) will read all available digits, and if the input is not a digit at all [and not a whitespace character, which are skipped over by cin >>
], then it keeps repeatedly trying to read the input.
It's not clear from your question exactly what you want to do when the user has entered "askjhrgAERY8IWE" to your program - there are two solutions that come to mind:
Alt 1. Ask again after removing the errant input. This is probably right for this application as it is interactive, but a terrible idea for an automated program that reads its input from a file.
if(!(cin >> num))
{
cout << "That deoesn't seem to be a number..." << endl;
cin.clear();
cin.ignore(10000, '\n');
}
Alt 2. Exit with an error message. This is clearly the right thing when the typical input is a datafile.
if(!(cin >> num))
{
cout << "That deoesn't seem to be a number..." << endl;
exit(1);
}
You should also add code to deal with end of file in this code - for file-input that should be acceptable [unless the file has specific data to mark the end]. For interactive input (where the user is typing directly to the program), end of file may or may not be considered an error - really depends on what happens next.