[英]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. 我无法弄清楚为什么在for循环之后,程序控制没有到达第三个printf。
Why won't the third printf
print? 为什么第三张
printf
打印?
If I change the for loop to while loop, it still will not print. 如果我将for循环更改为while循环,它将仍然无法打印。
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()
. 一旦
getchar()
EOF
检测为输入,则for
循环应结束。
EOF
is Control-Z
( ^Z
) under Windows and Control-D
( ^D
) under Linux/Unix. EOF
在Windows下是Control-Z
( ^Z
),在Linux / Unix下是Control-D
( ^D
)。 Once I enter this, the loop terminates and I get the final printf()
to display its output. 输入此内容后,循环终止,并得到最终的
printf()
以显示其输出。
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): 作为最后的说明(如@DanielFisher所述),在最终的
printf()
调用的末尾添加一个'\\n'
,因为您的特定实现可能会要求它,否则程序的行为可能是不确定的(感谢@ KeithThompson和@AndreyT在评论中指出了这一点):
printf ("Why does this work, nc = %f\n", nc);
printf
is buffered, that's why the final line may not be displayed. printf
被缓冲,这就是为什么最后一行可能不显示的原因。 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). 这意味着对
printf
的调用可能不会导致直接输出,因为该函数会在将数据放入输出(您的终端)之前累积数据。
A call to fflush
after your last printf will put everything that remains in the buffer in your terminal. 在最后一个printf之后调用
fflush
会将所有保留在终端缓冲区中的内容放入。 Also, the buffer is flushed every time you ask for a newline. 另外,每次您请求换行符时都会刷新缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.