Why doesn't the program execute the final printf output?

I cannot understand why the program control does not reach the third printf right after the for loop.

Why is third printf printing?

If I changed the for loop to a while loop, it still won’t print.

Here is the program and conclusion:

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

Output:

 Why does this work, nc = 0.000000 test 0 1 2 3 4 
0
source share
2 answers

It works great for me, how are you trying to complete the program? for -loop should end once EOF is defined as getchar() input.

EOF - Control-Z ( ^Z ) on Windows and Control-D ( ^D ) on Linux / Unix. As soon as I get into this, the loop ends and I get the final printf() to display its output.

As a final note (as @DanielFisher was also mentioned), add '\n' to the end of your final printf() call, as this may be required by your specific implementation or else the program behavior may be undefined (thanks @KeithThompson and @AndreyT, specifying this in comments):

  printf ("Why does this work, nc = %f\n", nc); 
+4
source

printf buffered, so the final line may not be displayed. This means that calling printf may not lead to direct output, since the function accumulates data before placing it in the output (your terminal).

Calling fflush after your last printf has placed everything that remains in the buffer in your terminal. In addition, the buffer is flushed every time you request a new line.

0
source

Source: https://habr.com/ru/post/955569/


All Articles