简体   繁体   English

C删除printf输出

[英]C remove printf output

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. 最好的情况是一些ANSI C,该程序应可在linux和Windows上运行。

I have found some escape sequences like "\\033[J" , but it dose not work. 我发现了一些转义序列,例如"\\033[J" ,但是它不起作用。

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. 如果我使用三个\\b我什么也不会得到。

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. i =当前位置。 n = max runs. n =最大运行次数。

I use 4 \\b because, at the first call of the function it will remove 4 spaces. 我使用4 \\b因为在该函数的第一次调用中它将删除4个空格。

Greetz. 格蕾兹

\\b is the escape sequence for backspace. \\b是退格的转义序列。 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%. 这应该打印98%,然后将其替换为99%。

What you look for is \\r it is Carriage Return. 您要寻找的是\\r这是回车票。 Makes the carriage go back to the beginning of the line. 使笔架返回到行的开头。 Do not use \\n as it will go down one line. 请勿使用\\n因为它将下降一行。

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. 因为\\ r不会删除文本,而只是允许您覆盖,所以必须确保打印足够的文本(如果需要,可以留空格)以清除行。

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

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