Do loop, check if input is what I want

Here is a easy program which I want the user to choose from number 1 to 5. But if the user input a string, like "a" "dsaf" or something. The program just processed without stop. Anyone who can solve it? I want when the user input a string, it will go back and prompt the user to input the integer. Thanks first!~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main ()
{
    int choice;
    do
    {
        cout << "Please input your choice(1-5): " << endl;
        cin >> choice;
    }while(choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 5);
    cout << "choice is " << choice <<  endl;
    return 0;
}
you can solve this by reading the input as a string and then parsing it with strtol() to check if it an integer.

if strtol() returns 0, it indicates that the input was not an integer. Google the strtol() function for more details.
Hi,

I really dislike no hate constructs like on line 10. They are ugly, error prone & not scalable.

Much better to do a switch or an if else if else chain.

It may be more code, but is way better IMO.

The else in the if statement and the default: in the switch perform the same thing: they catch anything not allowed for in the previous part of the statement. So you still stay with the int or char type.

Note that switch uses constant int or char types which are known at compile time: so if using other types, one must use the if statement.

hope all goes well.

Topic archived. No new replies allowed.