Skip to content
Advertisement

Adding a status bar to c++ console applications

I am making a linux application using C++ and it will print info out to the console. Parts of the program will take a while to compute and I would like to add a status bar in the console similar to the one used in wget (I put my own depiction below).

%complete[===========>               ] eta

What would be the best way to accomplish this goal? Are there any useful libraries that make it easy to add this functionality?

Advertisement

Answer

If your program is like wget, that is, it’s basically a batch program without the need for a full-screen UI (for which I would recommend ncurses), you can use the trick to print a carriage return (but not line feed) after your line; the next thing you write will overwrite the same line.

Here’s a demonstration.

#include <iostream>
#include <unistd.h>

int main(void)
{

        for (int i = 0; i < 10; i++) {
                std::cout << "Status: " << i << "r" << std::flush;
                sleep(1);
        }
        std::cout << "Completed.n";
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement