Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing progress in command-line application

Tags:

c++

c

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:

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?

like image 534
Eugene Loy Avatar asked May 21 '12 08:05

Eugene Loy


2 Answers

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

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

Print newline ('\n') when done.

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

like image 180
Some programmer dude Avatar answered Nov 17 '22 12:11

Some programmer dude


Use a carriage return.

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

Goes to the beginning of the line.

like image 6
shkschneider Avatar answered Nov 17 '22 11:11

shkschneider