printf具有无限while循环的异常行为

Des*_*PRG 6 c printf while-loop

当我运行以下程序时,我没有得到任何输出.

#include <stdio.h>

int main()
{
    printf("hello");
    while(1)
    {

    }   
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

而如果我编辑printf命令在字符串的末尾添加一个'\n'字符,那么预期的输出就会出现.第一个代码中发生了什么?我简直无法理解.

unw*_*ind 11

这是因为stdout是行缓冲的,即输出不会写入设备(终端),直到收集完整行.

您可以调用fflush(stdout);以强制刷新缓冲区到终端.不要试图冲洗stdin,这是不允许的.

  • 当程序不久后终止时,操作系统肯定会更快地刷新输出缓冲区,而不是没有刷新请求和程序继续. (3认同)