2014-09-02 84 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