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'
。