Hey guys, I was just wondering if there is a way in C++ to stop a program from crashing if the user enters a char instead of an int by mistake?

Thanks in advance.

The foolproof way is to take a string input (chars) and then parse the input character by character to determine if the input is valid through use of the functions in the <ctype> library.

int isdigit(char c);
int isalpha(char c);

Those return 1 if true, and 0 if not.

Thank you for the quick reply.

No problem... You'll still have to to a conversion between the character digits and integers. Just subtract '0' (the character zero) from the character digit, and it'll give the correct integer result.

Edit:
Or, if you're dealing with double-digit(or more) numbers, you might want to first check for the valid input then use the

int atoi(const char*s);

from <stdlib> to get your character string converted to the correct integer.

>stop a program from crashing if the user enters a char instead of an int by mistake?
The program shouldn't crash simply by reading the wrong type. Now, when you actually try to use the value you'll have issues if the variable wasn't initialized to something predictable. Post your code, because this problem usually must be solved on a case by case basis. However, there are two options for avoiding it:

1) Loop on failure:

int val;

while ( !( cin>> val ) ) {
  cerr<<"Invalid input, try again: ";
  cin.clear();
  cin.ignore ( numeric_limits<streamsize>::max(), '\n' );
}

2) Only use string input (there are many variations):

string line;
int val;

getline ( cin, line );
val = static_cast<int> ( strtol ( line.c_str(), 0, 0 ) );

Thanks for the replys I don't actually have any code at the moment but I was working on a program a few months ago (i'm only a beginner) I was using MSVC6 to create the program which had a menu so that the user could enter a number for what they wanted to do. When testing the program I hit a character by mistake and the program just seemed to go into an endless loop.

I am trying to improve my C++ so I will set myself a task soon so I can try out your ideas.

Thanks again.

>I hit a character by mistake and the program just seemed to go into an endless loop.
Then you want the first option. Because cin expects a valid number, and what you typed was not a valid number, it was never extracted from the stream and cin keeps failing on it. So you need to detect that cin failed, then clear any stream errors, and finally remove the faulty input so you can try again.

>int atoi(const char*s);
Don't ever use this function unless you're sure the string will be converted without fail. atoi has undefined behavior when it can't convert the string.

This article has been dead for over six months. Start a new discussion instead.