1

For the following code: (assuming x has been defined)

scanf("%d\n", &x);
printf("foo");

I expect the program to print foo if I press 1 and ENTER, but this is not the case. I have to press 1, ENTER, 2, ENTER to see it print foo.

Now the question is why do I need to input something plus another ENTER to make scanf return? It could't be that scanf just need one more ENTER than in the format string because pressing 1, ENTER, ENTER won't work either. In fact, scanf will keep waiting no matter how many ENTERs I entered until I type in something else.

I have tried this example in Visual Studio 2010 and MinGW, and they produced the same result. So how can this be explained? Is this Windows-specific? or compiler dependent? or just this kind of usage of scanf yields undefined behavior?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
weidi
  • 852
  • 7
  • 20

1 Answers1

5

The '\n' in the scanf format string (as well as space, tab, '\r', '\f', and '\v') makes scanf ignore whitespace.

ENTER is whitespace, so scanf ignores as much of it as it can and only stops when it sees something not whitespace (the 2).

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 1
    POSIX says it like this: "A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread." (http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html) – Mat Apr 22 '12 at 15:30
  • 1
    @pmg Thank you. so according to that description of \n, a \n in a format string doesn't necessarily mean that the user must use a \n as input. Everything that counts as white space will be matched with \n, is that right? – weidi Apr 22 '12 at 15:43
  • 1
    That is correct. Also many conversion specifications work by ignoring leading whitespace: eg `"%d"` is the same as `" %d"` same as `"\n%d"` same as `"\n\r\v\t \n\n\n%d"` and it matches `42` or `42` – pmg Apr 22 '12 at 15:46