Hi!
How do i prevent a program to crash if it expects and int and receives in the input a char?
and vice versa?
Thanks
Printable View
Hi!
How do i prevent a program to crash if it expects and int and receives in the input a char?
and vice versa?
Thanks
cin.ignore(putshizhere) I think
>How do i prevent a program to crash if it expects and int and receives in the input a char?
The same way you prevent a crash for anything else. You prepare for it:
The !() wrapper around the input request basically says "did this request fail?". The cin.clear() part clears the error state of reading an unexpected character. If you don't do that, you won't be able to do much else with the stream. The cin.ignore part reads and discards whatever is left in the stream, up to either BIG_NUMBER characters, or a newline. It's much better to use the maximum value of the stream size than to guess at the value of BIG_NUMBER, which would look more like this (you have to include <limits>, for numeric_limits<> and <ios>, for streamsize):Code:int x;
while ( !( cin>> x ) ) {
cerr<<"Invalid input\n";
cin.clear();
cin.ignore ( BIG_NUMBER, '\n' );
}
The other way around is harder because a numeric digit is still a valid character. In that case, you need to validate your input one way or another. The FAQ at www.cprogramming.com has a number of ways to go about that, and it's very application specific.Code:int x;
while ( !( cin>> x ) ) {
cerr<<"Invalid input\n";
cin.clear();
cin.ignore ( numeric_limits<streamsize>::max(), '\n' );
}
A common question that follows this one is how to handle the case when the user types other things after the int, like 148abc. It only takes a small change to Prelude's code:Code:while ( !( cin>> x ) || cin.get() != '\n' ) {
cerr<<"Invalid input\n";
cin.clear();
cin.ignore ( numeric_limits<streamsize>::max(), '\n' );
}
Great!!
Thanks
:)