Hello everyone. I'm new in C++ and just discovered this website a couple days ago.
English in not my native language so I hope you're not gonna be too harsh on me !
I would like to know how if/else statements work ?
More specificaly : How can I tell my program to authorize only one type of input ?
Explanation :
I'm doing a "mini-crappy-game" where the user needs to enter a number.
But i'm always afraid of the user's input.
Like, if the user type something he's not supposed to, when I usually write my code, I even tend to use "string" to ask for an int.. It's pretty hard to explain when I don't really know the subject mysel so I'll just show you some examples :
I'm trying to choose the level of difficulty.
The user have to type a number (1 to 5) to choose.
(PS : This is an example, if there's little error, don't mind them, I wrote it to explain my problem)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int level(0);
bool levelChoosen = false;
cout << "Welcome, please choose a difficulty level" << endl;
cout << "(1) = Easy" << endl;
cout << "(2) = Medium" << endl;
cout << "(3) = Hard" << endl;
cout << "(4) = Nightmare" << endl;
cout << "(5) = INSANE" << endl;
do {
cin >> level;
if (level == 1)
{
cout << "You choose the first level of difficulty" << endl;
levelChoosen = true;
}
else
{
cout << "Please try again" << endl;
}
}while(!levelChoosen);
|
Now, with this kind of code, if the user's input is not a number or if the number is too "high", the console will just repeat infinitely the thing which is in the else statement.
Like, If the user's input is "aze", the result will be :
Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
etc...
I would like to know if there's a possibilty using something to tell the code "If the user's input is not a number, then go in the else." I already tried some things like "isdigit" etc, but couldn't make the code work :(