问题描述
我正在用 C++ 编写一个控制台程序来下载一个大文件.我知道文件大小,并且我启动了一个工作线程来下载它.我想显示一个进度指示器,让它看起来更酷.
I'm writing a console program in C++ to download a large file. I know the file size, and I start a work thread to download it. I want to show a progress indicator to make it look cooler.
如何在不同的时间,但在相同的位置,在 cout 或 printf 中显示不同的字符串?
How can I display different strings at different times, but at the same position, in cout or printf?
推荐答案
使用固定宽度的输出,使用如下所示的内容:
With a fixed width of your output, use something like the following:
float progress = 0.0;
while (progress < 1.0) {
int barWidth = 70;
std::cout << "[";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " %
";
std::cout.flush();
progress += 0.16; // for demonstration only
}
std::cout << std::endl;
http://ideone.com/Yg8NKj
[> ] 0 %
[===========> ] 15 %
[======================> ] 31 %
[=================================> ] 47 %
[============================================> ] 63 %
[========================================================> ] 80 %
[===================================================================> ] 96 %
请注意,此输出显示彼此低一行,但在终端模拟器中(我认为也在 Windows 命令行中)它会打印在同一行.
Note that this output is shown one line below each other, but in a terminal emulator (I think also in Windows command line) it will be printed on the same line.
最后,不要忘记在打印更多内容之前打印换行符.
At the very end, don't forget to print a newline before printing more stuff.
如果你想删除最后的栏,你必须用空格覆盖它,打印更短的东西,例如完成."
.
If you want to remove the bar at the end, you have to overwrite it with spaces, to print something shorter like for example "Done."
.
此外,当然可以在 C 中使用 printf
来完成同样的操作;修改上面的代码应该很简单.
Also, the same can of course be done using printf
in C; adapting the code above should be straight-forward.
这篇关于如何在纯 C/C++ (cout/printf) 中显示进度指示器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!