I am confused about scanf\'s behaviour in the following program. scanf appears to input once, and then not input again, until a stream of characters is printed.
Belo
If scanf
sees a character in the input stream that doesn't match the conversion specifier, it stops the conversion and leaves the offending character in the input stream.
There are a couple of ways to deal with this. One is to read everything as text (using scanf
with a %s
or %[
conversion specifier or fgets
) and then use atoi
or strtol
to do the conversion (my preferred method).
Alternately, you can check the return value of scanf
; it will indicate the number of successful conversions. So, if scanf("%d", &i);
equals 0, then you know there's a bad character in the input stream. You can consume it with getchar()
and try again.