How to display a progress indicator in pure C/C++ (cout/printf)? How to display a progress indicator in pure C/C++ (cout/printf)? c c

How to display a progress indicator in pure C/C++ (cout/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) << " %\r";    std::cout.flush();    progress += 0.16; // for demonstration only}std::cout << std::endl;

http://ideone.com/Yg8NKj

[>                                                                     ] 0 %[===========>                                                          ] 15 %[======================>                                               ] 31 %[=================================>                                    ] 47 %[============================================>                         ] 63 %[========================================================>             ] 80 %[===================================================================>  ] 96 %

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.".

Also, the same can of course be done using printf in C; adapting the code above should be straight-forward.


You can use a "carriage return" (\r) without a line-feed (\n), and hope your console does the right thing.


For a C solution with an adjustable progress bar width, you can use the following:

#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"#define PBWIDTH 60void printProgress(double percentage) {    int val = (int) (percentage * 100);    int lpad = (int) (percentage * PBWIDTH);    int rpad = PBWIDTH - lpad;    printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");    fflush(stdout);}

It will output something like this:

 75% [||||||||||||||||||||||||||||||||||||||||||               ]