0

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
3
  • Try adding a newline to the last printf. Commented Jun 30, 2012 at 21:26
  • this may answer your question: stackoverflow.com/a/1716621/748875 Commented Jun 30, 2012 at 22:15
  • Out of interest: why double for nc? Surely an int would be more traditional? Commented Jul 2, 2012 at 10:56

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

8 Comments

The trailing \n isn't just stylistic. It's implementation-defined whether a trailing '\n' is required. If it is required, failing to provide one makes the program's behavior undefined.
@KeithThompson Interesting, could you elaborate on this requirement, I hadn't heard about this before. Does it have to do with whether it causes the output buffer to be flushed?
@Levon: The language specification states in 7.19.2/2 with regard to text streams: "Whether the last line requires a terminating new-line character is implementation-defined."
Why the downvote? I'd be happy to improve the answer or correct any errors, but It's not useful to OP, SO or me without an explanation.
@AndreyT Thanks .. I just found it and read up on it. Eliminated all references to stylistic :)
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.