0
votes

The documentation on scanf says that any "Non-whitespace character" in the format, causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

However, if I run:

int x;
while(scanf("\n%d",&x)==1) printf("%d\n",x);

with the following input:

1 2

It prints:

1
2

Given that there's no '\n' preceding any of the two numbers, why does scanf read them? Isn't that against the docs?

2
newlines are considered whitespace and ignored by scanf.Marc B
Did you read the part about how scanf handles whitespace in the format?user2357112
Thanks both, Got it. The White space character section includes not only the <space>, but any "white space type character", which includes the new line. How do I mark the question as solved?Carlos Pinzón
" How do I mark the question as solved? " - You can accept the answer by AShelly that answers your question ;)Jesper Juhl
It is not even necessary to put "\n%d" since the %d format ignores leading whitespace anyway. "%d" is sufficient.Weather Vane

2 Answers

5
votes

At the same page that you link to and just before the paragraph you quoted, I see:

  • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

A \n is a whitespace character.

Hence, the call

scanf("\n%d",&x)

will extract and discard any number of whitespace characters from stdio before reading data into &x.

2
votes

\n is a whitespace character. See isspace()