c++ - 在命令行应用程序中显示进度

标签 c++ c

好吧,问这么简单的事情我有点不好意思,但还是这样。

我有命令行实用程序,需要向用户显示进度。

我可以将进度写入 cout,如下所示:

std::cout << "10%\n";
...
std::cout << "20%\n";
...
std::cout << "30%\n";

...但结果用户会看到:

some line printed before
10%
20%
30%
...

...但我真正需要的是这个百分比得到了更新,就像一开始这样:

some line printed before
10%
...

...更新后:

some line printed before
20%
...

...第二次更新后:

some line printed before
30%
...

我应该如何做到这一点?

最佳答案

不要使用'\n',而是使用'\r':

std::cout << "\r10%" << std::flush;

完成后打印换行符('\n')。

使用 std::flush 很重要,这样才能真正输出流内容。

关于c++ - 在命令行应用程序中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10681530/

相关文章:

C++线程没有重载函数采用X参数

c - 为什么编译器将变量理解为指针,而事实并非如此?

使用 O3 优化级别编译 GSL

c - C程序编译警告:assignment makes pointer from integer without a cast [enabled by default]

c++ - 使用枚举基编写枚举时出现不明确的重载,但仅使用 clang

c++ - ComboBox初始化错误 : Cannot read property 'constructor' of undefined

c++ - 为没有继承的模板参数类提供构造函数

c - 返回浮点参数 f 的表达式 -f 的位级等价物

c - 我的程序不能很好地执行搜索功能。为什么?

c++ - SFINAE 函数根据模板类型返回正确的字符编码?