【发布时间】:2009-08-11 13:03:43
【问题描述】:
以下 C 程序不会在屏幕上打印任何内容。
我用gcc编译了程序:
#include<stdio.h>
main()
{
printf("hai");
for(;;);
}
【问题讨论】:
-
是的,它没有,你的问题是什么?
以下 C 程序不会在屏幕上打印任何内容。
我用gcc编译了程序:
#include<stdio.h>
main()
{
printf("hai");
for(;;);
}
【问题讨论】:
很可能,stdout 是行缓冲的。您的程序不会调用 fflush 或发送换行符,因此缓冲区不会被写出。
#include <stdio.h>
int main(void) {
printf("hai\n");
for(;;)
;
return 0;
}
另请参阅C FAQ 中的question 12.4 和What's the correct declaration of main()?。
【讨论】:
return 0?
这是由 stdio 中发生的缓冲引起的(即它不会立即输出,除非您通过包含 \n 或 fflush 来告诉它)。请参阅Write to stdout and printf output not interleaved 对此进行说明。
(p.s. 或者编译器对#include 中的错字不满意)
【讨论】:
默认情况下,标准输出往往是行缓冲的,因此您看不到任何内容的原因是您没有刷新该行。
这将起作用:
#include <stdio.h>
int main (int argC, char *argV[])
{
printf("hai\n");
for(;;)
;
return 0;
}
或者,您可以fflush 标准输出或只是摆脱无限循环以便程序退出:
#include <stdio.h>
int main (int argC, char *argV[])
{
printf("hai");
return 0;
}
但你可能还是想要换行符。
【讨论】:
你的 for(;;) 循环阻止流被刷新。正如其他人建议的那样,在输出的字符串中添加一个换行符,或者显式刷新流:
fflush( stdout );
在你的 printf 之后。并更正#include 的拼写。
【讨论】: