C 删除 printf 输出

发布于 2025-01-03 00:08:58 字数 736 浏览 1 评论 0原文

我想创建一个小函数,它应该在控制台中以百分比形式显示当前状态。该函数应该只显示该行中的当前值。 所以我必须删除最后一个输出。这可能吗?最好的情况是一些 ANSI C 的东西,该程序应该在 Linux 和 Windows 上运行。

我发现了一些转义序列,例如 "\033[J",但它不起作用。

编辑

好吧,我尝试了一下:

void PrintProcessBar(int i, int n) {
    float ratio = i / (float)n;    
    printf("%.3d\b\b", (int)(ratio * 100));
    fflush(stdout);
}

但它只是打印了很多零......出了什么问题?如果我使用三个 \b 我什么也得不到。

解决方案

float ratio = (i / (float)n) * 100;
printf("\b\b\b\b");
fflush(stdout);
printf("%.3d%c", (int)ratio, 37);        
fflush(stdout);

i = 当前位置。 n = 最大运行次数。

我使用 4 \b 因为,在第一次调用该函数时,它将删除 4 个空格。

问候。

I would like to create a small function, which should show the current status in percentage in the console. The function should only show the current value in the line.
So I have to remove the last output. Is that possible? The best case would be some ANSI C stuff, the program should work on linux and windows.

I have found some escape sequences like "\033[J", but it dose not work.

Edit

Well I tried it with:

void PrintProcessBar(int i, int n) {
    float ratio = i / (float)n;    
    printf("%.3d\b\b", (int)(ratio * 100));
    fflush(stdout);
}

But it just print lots of zeros... What went wrong? If I use three \b I get nothing.

Solution

float ratio = (i / (float)n) * 100;
printf("\b\b\b\b");
fflush(stdout);
printf("%.3d%c", (int)ratio, 37);        
fflush(stdout);

i = current position.
n = max runs.

I use 4 \b because, at the first call of the function it will remove 4 spaces.

Greetz.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往事风中埋 2025-01-10 00:08:58

\b 是退格键的转义序列。您可以将其与空格一起使用来删除行。

例如:

printf("98%");
fflush(stdout);
// sleep some time
printf("\b\b\b99%");
fflush(stdout);

这应该打印 98%,然后将其替换为 99%。

\b is the escape sequence for backspace. you can use it with spaces to delete a line.

For example:

printf("98%");
fflush(stdout);
// sleep some time
printf("\b\b\b99%");
fflush(stdout);

This should print 98%, and then replace it with 99%.

碍人泪离人颜 2025-01-10 00:08:58

您要查找的是 \r 它是回车符。使马车返回到行的开头。 不要使用\n,因为它会下降一行。

因为 \r 不会删除文本,而只是允许您覆盖,所以您必须确保打印足够的文本(如果需要,可以添加空格)来清除行。

What you look for is \r it is Carriage Return. Makes the carriage go back to the beginning of the line. Do not use \n as it will go down one line.

Because \r does not delete text but simply allows you to overwrite, you have to make sure you print enough text (spaces if you need) to clear your line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文