如何制作“进度条"使用printf? [英] How to make a "progress bar" using printf?
问题描述
许多命令行工具实现了基于文本的进度条.喜欢rpm安装:
<块引用>安装##############[45%]
#
随百分比增长,同时保持在一行.我想要的是类似的东西:我需要一个只占用一行的进度指示器,也就是说,当百分比增长时,它会被覆盖,而不是创建一个新行(\n
).>
我试过了:
#include 国际主要(){int i = 0;对于 (i = 0; i <10000; i++){printf("\r正在进行 %d", i/100);}printf("\n");}
\r
用于覆盖单行.但是,\r
将光标移至行首,printf
将光标移至行尾,导致光标快速摆动.大家稍微编译一下就可以感受到了.任何人都可以想出替代方法来避免这个问题吗?
这是缓冲 stdout
流的问题.您必须在 printf()
之后使用 fflush(stdout)
显式刷新它(使用 \n
进行隐式刷新):
fflush(stdout);
Many command line tools implement text-based progress bar. Like rpm installing:
installing ##############[45%]
the #
grows with the percentage, while keeps itself in a single line. What I want is something similar: I need a progress indicator taking just one line, that is to say, when percentage grows, it got overwritten, instead of make a new line(\n
).
I tried this:
#include <stdio.h>
int main (){
int i = 0;
for (i = 0; i < 10000; i++){
printf("\rIn progress %d", i/100);
}
printf("\n");
}
\r
works to overwrite the single line. However, \r
brings cursor to the beginning of line and printf
brings cursor to the end, which result in a rapidly waving cursor. You guys can feel it by a little compiling. Can Anyone come up with alternatives to avoid this issue?
This is a problem of the stdout
stream being buffered. You have to flush it explicitly (implicit flushing occurs with a \n
) using fflush(stdout)
after the printf()
:
fflush(stdout);
这篇关于如何制作“进度条"使用printf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!