为什么“printf"不产生任何输出? [英] Why does "printf" not produce any output?
问题描述
我正在学习用 C
编程.你能解释一下为什么这里什么都没有打印吗?
I am learning to program in C
. Could you explain why nothing is printed here?
#include <stdio.h>
int main (void)
{
char a[]="abcde";
printf ("%s", a);
}
推荐答案
在许多系统上 printf
被缓冲,即当你调用 printf
时,输出被放置在一个缓冲区中而不是立即打印.当您打印换行符 \n
时,缓冲区将被刷新(也就是打印的输出).
On many systems printf
is buffered, i.e. when you call printf
the output is placed in a buffer instead of being printed immediately. The buffer will be flushed (aka the output printed) when you print a newline \n
.
在所有系统上,尽管缺少 \n
,您的程序仍会打印,因为程序结束时缓冲区会被刷新.
On all systems, your program will print despite the missing \n
as the buffer is flushed when your program ends.
通常你仍然会添加 \n
像:
Typically you would still add the \n
like:
printf ("%s\n", a);
立即获得输出的另一种方法是调用 fflush
来刷新缓冲区.来自手册页:
An alternative way to get the output immediately is to call fflush
to flush the buffer. From the man page:
对于输出流,fflush() 强制写入所有用户空间给定输出的缓冲数据或通过流的更新流底层写函数.
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.
来源:http://man7.org/linux/man-pages/man3/fflush.3.html
编辑
正如@Barmar 指出并由@Alter Mann 引用的那样,程序结束时需要刷新缓冲区.
As pointed out by @Barmar and quoted by @Alter Mann it is required that the buffer is flushed when the program ends.
引自@Alter Mann:
Quote from @Alter Mann:
如果 main 函数返回到它的原始调用者,或者如果退出函数被调用,则在程序终止之前关闭所有打开的文件(因此所有输出流都被刷新).
If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination.
这篇关于为什么“printf"不产生任何输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!