while语句中的sleep函数

时间:2012-08-14 16:42:04

标签: c

我无法理解为什么这段代码不会每隔一秒打印当前时间。 这有什么问题?

#include <stdio.h>
#include <unistd.h>
#include <time.h>


int main(int argc, const char * argv[])
{
    while (1) {
        sleep(1);
        time_t tm;
        struct tm *t_struct;
        tm = time(NULL);
        t_struct = localtime(&tm);

        printf("%.2d:%.2d:%.2d", t_struct->tm_hour, t_struct->tm_min, t_struct->tm_sec);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:11)

stdout可能是行缓冲的,因此您可能需要在输出文本后fflush,或打印换行符以使更改可见。