显示命令行应用程序的进度

时间:2021-04-30 00:11:15

Ok, I am a bit embarrassed to ask such a simple thing but still.

好吧,我仍然有点尴尬地问这么简单的事情。

I have command line utility application and need to show progress to the user.

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

I could write progress into cout, like this:

我可以写进cout的进度,像这样:

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

... but as a result user will see:

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

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

... but what i really need is that percentage got updated, like this at the beginning:

...但我真正需要的是百分比得到更新,如下所示:

some line printed before
10%
...

... and after update:

......并在更新后:

some line printed before
20%
...

... and after second update:

...并在第二次更新后:

some line printed before
30%
...

How should I achieve that?

我该怎么做?

2 个解决方案

#1


24  

Instead of using '\n', use '\r':

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

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

Print newline ('\n') when done.

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

It's important to use std::flush so the stream contents really is output.

使用std :: flush非常重要,因此输出了流内容。

#2


6  

Use a carriage return.

使用回车。

std::cout << "\r10%";
std::cout << "\r20%";
...

Goes to the beginning of the line.

走到行的开头。

#1


24  

Instead of using '\n', use '\r':

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

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

Print newline ('\n') when done.

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

It's important to use std::flush so the stream contents really is output.

使用std :: flush非常重要,因此输出了流内容。

#2


6  

Use a carriage return.

使用回车。

std::cout << "\r10%";
std::cout << "\r20%";
...

Goes to the beginning of the line.

走到行的开头。