简体   繁体   中英

Why does program not execute final printf statement?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM