How to display a progress indicator in pure C/C++ (cout/printf)?(如何在纯 C/C++ (cout/printf) 中显示进度指示器?)
问题描述
我正在用 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) 中显示进度指示器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在纯 C/C++ (cout/printf) 中显示进度指示器?
				
        
 
            
        - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 从python回调到c++的选项 2022-11-16
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 - Stroustrup 的 Simple_window.h 2022-01-01
 - 近似搜索的工作原理 2021-01-01
 - C++ 协变模板 2021-01-01
 - STL 中有 dereference_iterator 吗? 2022-01-01
 - 静态初始化顺序失败 2022-01-01
 
						
						
						
						
						
				
				
				
				