问题
I cannot figure out why program control does not reach the third printf, right after the for loop.
Why won't the third printf print?
If I change the for loop to while loop, it still will not print.
Here is the program and output:
main()
{
double nc;
printf ("Why does this work, nc = %f\n", nc);
for (nc = 0; getchar() != EOF; ++nc)
{
printf ("%.0f\n", nc);
}
printf ("Why does this work, nc = %f", nc);
}
The output is:
Why does this work, nc = 0.000000
test
0
1
2
3
4
回答1:
It works fine for me, how are you trying to termintate the program? The for-loop should end once EOF is detected as input by getchar().
EOF is Control-Z (^Z) under Windows and Control-D (^D) under Linux/Unix. Once I enter this, the loop terminates and I get the final printf() to display its output.
As a final note (as mentioned by @DanielFisher too), add a '\n' at the end of your final printf() call as it may be required by your particular implementation or otherwise the program's behavior might be undefined (thanks to @KeithThompson and @AndreyT pointing this out in the comments):
printf ("Why does this work, nc = %f\n", nc);
回答2:
printf is buffered, that's why the final line may not be displayed.
That means a call to printf may not result in a direct output as the function accumulates data before putting it in the output (your terminal).
A call to fflush after your last printf will put everything that remains in the buffer in your terminal. Also, the buffer is flushed every time you ask for a newline.
来源:https://stackoverflow.com/questions/11277796/why-does-program-not-execute-final-printf-statement