2014-11-22 130 views
-2

为什么我的程序不是printf?Printf in C with using sleep not working

先睡着了,然后写道,但他应该这样做反过来..程序

#include <stdio.h> 
#include <stdlib.h> 
#ifdef _WIN32 
#include <Windows.h> 
#else 
#include <unistd.h> 
#endif 

void sleepMilliSecond(long milliSecondInput) { 
#ifdef _WIN32 
    Sleep(milliSecondInput); // v milliSecondach 
#else 
    usleep(pollingDelay * 1000); //microsekundy -> milisekundy 
#endif 
} 



int main(int argc, char** argv) { 
    printf("start sleep");  
    sleepMilliSecond(1000); //sleep 1s 
    printf("stop sleep"); 
    return (EXIT_SUCCESS); 
} 

输出是:睡觉,然后他开始写休眠停止睡眠,为什么呢?

编辑: 工作的解决方案是:

printf("start sleep");  
fflush(stdout); 
sleepMilliSecond(10000); 
printf("stop sleep"); 
+0

适合我! – Rizier123 2014-11-22 12:44:41

+0

对于我来说不行,因为他在睡眠时间间隔后写入控制台“START SLEEP”:( – tilefrae 2014-11-22 12:45:37

+3

'printf'被缓冲。在第一个'printf'后面尝试'fflush(stdout)' – SleuthEye 2014-11-22 12:46:00

回答

4

printf是缓冲I/O。要强制缓冲区被写入输出,您可以这样拨打fflush

printf("start sleep"); 
fflush(stdout); 
sleepMilliSecond(1000); //sleep 1s 
printf("stop sleep"); 
4

你不冲水“停止睡眠”和“启动休眠”它仍然在缓冲区中。添加\ n到结尾:

printf(“start sleep \ n”);
printf(“stop sleep \ n”);

+0

@顺磁牛角面包不起作用fflush(stdout)帮助我。 – tilefrae 2014-11-22 12:53:04