Why does program not execute final printf statement?

放肆的年华 提交于 2019-12-18 09:46:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!