Whitespace before %c specification in the format specifier of scanf function in C

If you read the specification for scanf() carefully, most format specifiers skip leading white space. In Standard C, there are three that do not:

  • %n — how many characters have been processed up to this point
  • %[…] — scan sets
  • %c — read a character.

(POSIX adds a fourth, %C, which is equivalent to %lc.)

Input white-space characters (as specified by isspace) shall be skipped, unless the conversion specification includes a [, c, C, or n conversion specifier.

Adding the space between %d and %c means that optional white space is skipped after the integer is read and before the (not white space) character is read.

Note that literal characters in a format string (other than white space — for example, the X and Y in "X%dY") do not skip white space. Matching such characters does not count as a successful conversion either; they do not affect the return value from scanf() et al.

Leave a Comment