For most of its conversions, including %d
, scanf
starts by reading and ignoring initial white-space characters, including the new-line character. Only for the conversions with [
, c
, or n
does it not skip white-space characters.
To tell scanf
to skip white-space characters before processing %c
, insert a space in the format: scanf(" %c", &b);
.
Most scanf
formats will read and discard leading white space (e.g. space, tab, and newline).
So, in the shown code, the newline will be left after the first call to scanf
. But the second call to scanf
will read and discard it. However, the newline after that input will be left in the input buffer.
The only three scanf
formats that do not read and discard leading white space are %c
, %[…]
(scan sets) and %n
. If you want the same behavior for those formats, you need to add an explicit leading space in the format string yourself.
Because error handling and invalid input could be hard to handle with scanf
, I always recommend using fgets
to read a whole line instead. Then, you can use, e.g. sscanf
to parse the line.
This way, if there's invalid input, it will not be left in the input buffer.