繁体   English   中英

如何在 C 的单行上制作倒数计时器打印结果?

[英]How to make countdown timer print result on single line in C?

我在这里有代码,它可以用作倒数计时器,但它会在新行上打印结果,如下所示:

10
9
8
7
6
5
4
3
2
1

这是我的代码:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

到目前为止,我尝试将 \n 更改为 \r 以在一行上打印,但它不起作用。 我正在尝试清除该行并打印该行中的下一个数字,然后清除该数字并在有意义的情况下打印下一个

尝试更改printf("Time: \t%d \n", count); to printf("Time: \t%d \t", count);

使用"\b \b"清除一个字符。 想象一下,您刚刚打印了“42”:第一个'\b'将 cursor 移回 2 上方,然后空格“清除”那个 2,最后 go 再回到一个空格。

    printf("Time: \t");
    while(count != 0)
    {
            printf("%d", count);
            fflush(stdout);
            sleep(1);
            if (count >= 100) printf("\b \b");
            if (count >= 10) printf("\b \b");
            if (count >= 1) printf("\b \b");
            count--;
    }
    printf(" \n");

尝试在您的printf中使用\r后添加fflush(stdout) ,如 pmg 所述:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \r", count);
                fflush(stdout);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM