Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C while语句中的sleep函数_C - Fatal编程技术网

C while语句中的sleep函数

C while语句中的sleep函数,c,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 = tim

我不明白为什么这段代码没有每秒打印一次当前时间。 这里有什么问题

#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;
}
#包括
#包括
#包括
int main(int argc,const char*argv[]
{
而(1){
睡眠(1);
时间;
结构tm*t_结构;
tm=时间(空);
t_struct=localtime(&tm);
printf(“%.2d:%.2d:%.2d”,t\u结构->tm\u小时,t\u结构->tm\u分钟,t\u结构->tm\u秒);
}
返回0;
}

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

@Levon,为什么要这样做?@Levon这不重要-这就是编译器的用途。它会自动将声明从循环中拉出。您能建议我如何以单行而不是多行显示当前时间吗?@rogi,这取决于您的运行环境;但是,您可以尝试使用
fflush(stdout)
(显示当前时间),然后在打印新时间之前打印回车符
'\r'