-
July 3rd, 2010, 10:28 AM
#1
char input error help
hi i tried a program wherein i declared an int variable. after running the program, whenever i input a character or string to the input variable, the program crashes. how could i prevent a user from inputting a character to the int variable? thanks
EDIT: I'm using C.
Last edited by rukix1x; July 3rd, 2010 at 11:10 AM.
-
July 3rd, 2010, 10:31 AM
#2
Re: char input error help
One option is to read into a string, initialise a stringstream with that string, and then read from the stringstream into your int variable. You then check if the stringstream is in an error state after extracting from it.
Alternatively, you continue to read directly into the int variable, but you check if the input stream is in an error state after extracting from it. If so, you clear the error state, discard characters (use the ignore member function) from the input stream, and continue reading.
-
July 4th, 2010, 12:54 AM
#3
Re: char input error help
im using c so how do i do it with c?
-
July 4th, 2010, 12:57 AM
#4
Re: char input error help
The basic thing is that you need to verify that the input was what you thought it was. There are two ways to do this.
First, you could do essentially the same thing (read into a string, the process it) except using a fixed-size char array rather than the safer std::string since you're in C.
Second, you could simply test the return value from scanf() to see if all expected conversions were successful. Note: if they weren't, you'll need to dispose of the troublesome characters in some way. A bunch of fgetc() calls will usually do the trick.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|