c语言倒计时输入字符中止,如何在C语言中让倒计时器在单行上打印结果?

我有一段代码,它可以作为一个倒计时器,但它打印的结果在一个新的行,像这样。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("

");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值