Printf和睡在For Loop里面?

人气:371 发布:2022-10-16 标签: linux c sleep

问题描述

我不明白为什么下面的代码是这样工作的.我的意思是:不是在每一秒延迟后打印"Hello"...它等待5秒并立即显示hellohellohellohellohello

#include <stdio.h>

int i;
for(i=0; i<5; i++) {
   printf("hello");
   sleep(1);
}       

推荐答案

如果输出要发送到TTY,printf()(stdout)的输出默认情况下是行缓冲的。您需要

中的一个
printf("hello
");

printf("hello");
fflush(stdout);

后者将在每次迭代中显式刷新输出。

210