Q:

What's the behavior of scanf when the format string ends with a newline?

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?

A:

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).

