C validating input char

" " reads input up to the first non-whitespace character."%c" reads a single character, which may or may not be whitespace.the problem now is that if i type in negative value or a character i won't get a correct output.so i came up with this validation : which is not efficient at all.

I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried: might be better.

Just for example, if user inputs 'abc' an error is caught, but if user inputs '432' the program hangs. Thanks, Bill #include The problem is that scanf() eats whitespace, so the newline is consumed if you enter a valid number, but not if you enter alphabetical characters (because the function stalls on the first non-digit).

Then the program hits the getchar() lines, because only one field has been converted.

So if the user types "432" followed by a newline, the "%f" consumes the "432", and the " " consumes the newline (and any whitespace following it).

As soon as the user types a non-whitespace character (such as 'F' or 'C'), the scanf() will consume it and finish.

Leave a Reply

  1. Person to person sexcam 03-Nov-2017 13:42

    This web site provides free sex chat rooms without any registration being needed. When you are looking for a free online sex chat room with no registration, you want to find a place that is not going to require you pay fees, or give away your email address.