【问题标题】:Why does the following program not generate any visible output?为什么以下程序不生成任何可见的输出?
【发布时间】:2009-08-11 13:03:43
【问题描述】:

以下 C 程序不会在屏幕上打印任何内容。

我用gcc编译了程序:

#include<stdio.h>

main()
{
    printf("hai");
    for(;;);
}

【问题讨论】:

  • 是的,它没有,你的问题是什么?

标签: c printf


【解决方案1】:

很可能,stdout 是行缓冲的。您的程序不会调用 fflush 或发送换行符,因此缓冲区不会被写出。

#include <stdio.h>

int main(void) {
    printf("hai\n");
    for(;;)
    ;
    return 0;
}

另请参阅C FAQ 中的question 12.4What's the correct declaration of main()?

【讨论】:

  • 为什么投反对票?未能从永不返回的函数中包含return 0
  • @faceless 我最初错过了错字。人脑就是这样:当你最不希望它们自动纠错时,它们会自动纠错。如果您对我的回答投了反对票,请指出我错过了错字。
【解决方案2】:

这是由 stdio 中发生的缓冲引起的(即它不会立即输出,除非您通过包含 \n 或 fflush 来告诉它)。请参阅Write to stdout and printf output not interleaved 对此进行说明。

(p.s. 或者编译器对#include 中的错字不满意)

【讨论】:

    【解决方案3】:

    默认情况下,标准输出往往是行缓冲的,因此您看不到任何内容的原因是您没有刷新该行。

    这将起作用:

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

    但你可能还是想要换行符。

    【讨论】:

      【解决方案4】:

      你的 for(;;) 循环阻止流被刷新。正如其他人建议的那样,在输出的字符串中添加一个换行符,或者显式刷新流:

      fflush( stdout );
      

      在你的 printf 之后。并更正#include 的拼写。

      【讨论】:

        猜你喜欢
        • 2011-04-23
        • 2014-09-13
        • 1970-01-01
        • 2018-05-13
        • 2017-01-03
        • 2023-01-02
        • 2019-07-06
        • 2018-01-23
        • 2014-01-08
        相关资源
        最近更新 更多