Why we need to put space before %c? [duplicate]

Adding the space to the format string enables scanf to consume the newline character from the input that happens everytime you press return. Without the space, name[i] will receive the char '\n', and the real char is left to be misinterpreted by %f.

So, say your input is

a 1.0 2
b 3.0 4
c 5.0 6

The program sees it more like this:

a 1.0 2\nb 3.0 4\nc 5.0 6\n\377

That is, the line-breaks are actual characters in the file (and the \377 here indicates “end of file”).

The first scanf will appear to work fine, consuming a char, a float, and an integer. But it leaves the input like this:

\nb 3.0 4\nc 5.0 6\n\377

So the second scanf will read the '\n' as its %c, unless you get rid of it first.

Adding the space to the format string instructs scanf to discard any whitespace characters (any of space ' ', tab '\t', or newline '\n').

A directive is one of the following:

  • A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

from http://linux.die.net/man/3/scanf


This sort of problem arises whenever you use scanf with %c in a loop. Because, assuming free-form input, newlines can happen anywhere. So, it’s common to try to avoid the whole issue by using a two-tiered approach. You read lines of input into a buffer (using fgets); chop-off the silly newline characters; then use sscanf instead of scanf to read from the buffer (string) instead of straight from the file.

Leave a Comment