Reputation: 5794
I wrote this code:
scanf("%d \n", &n);
for(i=0;i<n;i++)
printf("%d \n",i);
It was not printing. I realised that there was a '\n' in the call to scanf. When I removed that I got the expected output. Why was it not giving the output when the scanf format string contained a '\n'?
What is the reason?
Upvotes: 0
Views: 480
Reputation: 10839
scanf has an implicit read to end of line. Since you had a '\n' in your format string, it was reading your first return as part of the format. It was then continueing to wait for the '\n' it expected as a terminator. If you provided another token, followed by a return, then you would get the expected results.
So, if you supplied:
2
7
You would get the output:
0
1
Because, the first number (2), has been matched against your first format specifier. What I'm unsure about is why you need to provide another token (just pressing return on the subsequent line doesn't work). I assume that's because scanf requires a minimum of one non-white space character, but I could be wrong.
Upvotes: 2