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.