What you could do is write a small function to get an integer (or a double) with suitable error handling.
A simple example
1 2 3 4 5 6 7 8 9 10
|
int get_integer()
{
int num = 0;
while (!(cin >> num)) // get the input and test the outcome
{
cin.clear(); // reset error flags
cin.ignore(1000, '\n'); // remove invalid characters from buffer
}
return num; // we get here, everything was ok.
}
|
you would insert that into your code somewhere just before the start of main().
Then where you have
1 2 3
|
cout << "What would you like to do? ";
cin >> choice;
|
it now becomes:
1 2 3
|
cout << "What would you like to do? ";
choice = get_integer();
|
Explanation
If the user enters something which is not an integer, the
cin
stream enters a fail condition, which means no further input is possible. You might write that as
1 2 3 4 5
|
cin >> choice;
if (!cin)
{
cout << "an input error occurred";
}
|
In the function get_integer(), the input is done and the result tested inside the condition of the while loop.
Next, there are two steps which need to be done before the stream can be used again.
1. reset the error flags.
2. remove the unwanted characters typed by the user.
I used a function (a) to avoid cluttering the main code, (b) because there may be several places where user input is done, the function allows code to be re-used.
For the values of type
double
, you could replicate the function, give it a different name and change
int
to
double
. (You might also use a function template, but I didn't want to go into that as well here).