2014-09-02 52 views
2

我不明白为什么下面的代码工作像this..I平均:不是印刷“你好”每一秒的延迟后...它等待5秒和一次显示hellohellohellohellohello。睡在for循环

#include <stdio.h> 

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

你需要以某种方式刷新标准输出。 http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – 2014-09-02 15:56:59

+1

你不包括你的代码在一个'main'函数中...你真的编译和执行了吗? – Jay 2014-09-02 16:01:47

回答

4

printf不立即打印,而是每行缓存一行。

添加“\ n”(换行符)添加字符串printf("hello\n");的结尾或使用写入功能代替write(STDOUT_FILENO, "hello", sizeof("hello"));

9

printf()stdout)输出,如果输出是要一个tty是线默认缓冲。你需要的

printf("hello\n"); 

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

后者将明确地刷新输出每次迭代之一。

3

您正在写给标准输出(stdout),这是缓冲。如果您希望立即打印内容,则可以刷新输出或插入换行符。

您可以将\n添加到您的字符串的结束,以便打印换行符 - 改变你的printf行:

printf("hello\n"); 

进行冲洗就可以了stdout缓冲通话fflush,该printf后:

#include <stdio.h> 

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

通常输出可以被缓冲。这意味着在实际写入控制台之前,实现会收集几个字节。您可以通过fflush(stdout)明确写入缓冲区。所有文件描述符都是如此,其中之一是stdout,终端输出。您可以使用setbuff(stdout,NULL)禁用缓冲区,但这在性能方面几乎不是一个好主意。

0

试试这个:

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

请提供解释为什么这将解决问题的评论。 – 2014-09-02 16:36:47

+0

i = 0;阻止写作“你好”5次。 – 2014-09-02 16:52:17

+0

这不会产生预期的效果。它会导致循环永远运行(并在打印时保持打印“Hello”)。 OP仍然希望打印出“Hello”五次,但每次之间都有延迟。 – 2014-09-11 17:54:34