好吧,问这么简单的事情我有点不好意思,但还是这样。
我有命令行实用程序,需要向用户显示进度。
我可以将进度写入 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/