我用C语言编写了一个带有stdlib.h
头文件和time.h
头的计时器。我犯了个错误。如果你能帮我,我会很高兴的。我的代码是:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int s;
int m = 0;
while (s<=60)
{
system("clear");
printf("%d Minutes %d Seconds", m, s);
sleep(1000);
s+=1;
if (s==60)
{
m+=1;
s=0;
}
}
return 0;
}
该程序不显示任何输出,而不是显示空白屏幕。
发布于 2015-03-15 05:19:04
因为stdout的输出是line-buffered
,所以如果需要它更新行内的输出(在打印\n
之前),则需要用fflush()
刷新缓冲区。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int s = 0; // init it
int m = 0;
while (s <= 60)
{
system("clear");
printf("\r"); // move cursor to position 0
printf("%d Minutes %d Seconds", m, s);
fflush(stdout); // flush the output of stdout
sleep(1); // in seconds
s += 1;
if (s==60)
{
m+=1;
s=0;
}
}
return 0;
}
发布于 2015-03-15 05:13:18
sleep(1000)
将睡眠1,000秒钟。您还必须将s
初始化为零,因为您正在while
循环中读取它。sleep
是在unistd.h中定义的,所以您也应该包括它。
https://stackoverflow.com/questions/29060945
复制相似问题