int main()
{
short difficulty;
cout << "enter difficulty";
if (difficulty < 1 || difficulty > 3)
{
cout << "Enter a number between 1 and 3";
}
return 0;
}
if the user types in a letter or a symbol then show an error, how do I check if what the user enters is not a number?
if (difficulty < '1' || difficulty > '3')
{
cout << "Enter a number between 1 and 3";
}
doesnt seem to be working and I dont know how to use cin.fail() and googleing doesnt make sense. Why is this so hard? I just need to check if the number you enter is 1 or 3 and it cannot be a letter or a symbol. difficulty has to be 1,2 or 3, if its anythihng else then show a message.
I have a int variable and I want to give an error if you type in a letter or a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int difficulty;
cout << "enter a number";
cin >> difficulty;
do
{
cout << "Enter a number between 1 and 3";
cin >> difficulty;
}while (difficulty <1 || difficulty > 3);
// but I also want to check if x is a letter or a string, if it is then show an error message.
return 0;
}
how do I check if you type in a letter or a string instead of a number?
You are a life saver iHutch105, thanks, now I need to do this in reverse. Now I need to check for letters. I have a char variable and if the letter entered is not w,s,a, or d then show an error message? I dont quite understand what is going on in your code. help will be greatly appreciated.
Thank I love you man =) but I understand what is going, I would love some explanation so in the future if I have to do this kind of thing again, I can do it on my own. I got rid of
Ok. Since you've done if statements I'll assume you know what's going on with the switch statement in the ValidChar() function.
std::cin.clear() is clearing the error state flags for the cin buffer (it's setting it to goodbit here).
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); is just getting any remaining characters in the buffer and ignoring them. If you leave this out, there's a chance could end up in a weird loop or something like that. For the record, the first argument I'm passing in is the number of characters to get (in this case, I'm getting the max limit of a stream). The second is a delimiter. The function will get characters until either one of those arguments are hit.
Probably the weirdest thing is all of this is the !( std::cin >> c ) syntax. Without going into too much detail, there's a cast to a void pointer involved here which, in the if statement context, gets evaluated as a boolean value. If the stream is in a good state, then a non-null pointer is returned. If it's in a bad state it'll return a null pointer.
Hope this helps. If there's something in specific that you don't understand then just give me a shout.