The problem is that the
std::cin input stream goes into an error state when the user enters a character instead of a number. It goes into an error state because it's "smart" enough to recognize that
e isn't a number.
In the end, the problem is that you ask your user to input either a character or a number, but
std::cin only ever expects a number.
The "professional" approach would be to input a string, then search for patterns in it, preferably using the
regex library of C++11.
http://www.cplusplus.com/reference/regex/
The simpler approach would be to just make the program stop when anything other than a number is entered. You achieve this by checking the state of the input stream:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number or ANYTHING OTHER to exit:";
cin >> num;
while(cin.good())
{
cout << "Number entered was " << num << endl;
cout << "Enter a number or ANYTHING OTHER to exit:";
cin >> num;
}
return 0;
}
|
The above could be written more elegantly if you take advantage than an input stream can be converted to a boolean depending on its state. Meaning
std::cin becomes
false if it entered an error state, otherwise becomes
true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number or ANYTHING OTHER to exit:";
while(cin >> num)
{
cout << "Number entered was " << num << endl;
cout << "Enter a number or ANYTHING OTHER to exit:";
}
return 0;
}
|
Note that we no longer care if the user entered the character
e (although I believe the emphasis was obvious enough). If the user enters anything other than a number, the program quits.
See also:
http://www.parashift.com/c++-faq/stream-input-failure.html