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>
usingnamespace 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;
}
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 ifelseifelsechain.
It may be more code, but is way better IMO.
The else in the ifstatement 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 switchuses constant intor chartypes which are known at compile time: so if using other types, one must use the ifstatement.