我有一段代码,它可以作为一个倒计时器,但它打印的结果在一个新的行,像这样。10
9
8
7
6
5
4
3
2
1
这是我的代码int timer()
{
int count;
count = 10;
while(count != 0)
{
printf("Time: %d
", count);
count--;
sleep(1);
}
printf("
Count down timer has expired
");
return 0;
}
到目前为止,我试过把
改成,以便在一行上打印结果,但没有成功。我试图让它清除这一行并打印下一个数字,然后清除这一行并打印下一个数字,如果这有意义的话。
答案
尝试添加 fflush(stdout) 使用后 在你 printf 如 pmg 所述。int timer()
{
int count;
count = 10;
while(count != 0)
{
printf("Time: %d ", count);
fflush(stdout);
count--;
sleep(1);
}
printf("
Count down timer has expired
");
return 0;
}
另一答案
试着改变 printf("Time: %d
", count); 到 printf("Time: %d ", count);
另一答案
使用 " " 来清除一个字符。想象一下,你刚刚打印了 "42":第1个 '' 将光标移回2的上方,然后用空格 "清除 "2,最后再返回一个空格。printf("Time: ");
while(count != 0)
{
printf("%d", count);
fflush(stdout);
sleep(1);
if (count >= 100) printf(" ");
if (count >= 10) printf(" ");
if (count >= 1) printf(" ");
count--;
}
printf("
");