scanf() leaves the newline character in the buffer

The scanf() function skips leading whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don’t skip whitespace.

Use " %c" with a leading blank to skip optional white space. Do not use a trailing blank in a scanf() format string.

Note that this still doesn’t consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We’re just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.


Note that non-whitespace “directives” (to use POSIX scanf terminology) other than conversions, like the literal text in scanf("order = %d", &order); doesn’t skip whitespace either. The literal order has to match the next character to be read.

So you probably want " order = %d" there if you want to skip a newline from the previous line but still require a literal match on a fixed string, like this question.

Leave a Comment