GeoMint
GeoMint

Reputation: 169

Simple terminal progress bar in C++ (linux terminal)

I would like to make a progress bar in C++ that prints "Loading...".

The dots will be showed one per second.

Like Loading > Loading. > Loading.. > Loading... .

How i can do this?

Thank you.

Upvotes: 1

Views: 1458

Answers (2)

Christophe
Christophe

Reputation: 73587

You could use a thread to update every second the display.

Here a class to embed this:

#include <thread>   // for threads
#include <chrono>   // for expresssing duration
#include <atomic>   
#include <iomanip>
#include <functional>   // for std::ref()
using namespace std; 

class progress_bar {
    atomic<bool> finished; 
    atomic<int> n; 
    thread t;
public: 
    progress_bar() : finished(false),n(0), t(ref(*this)) { }    // initiate the bar by starting a new thread
    void operator() () {                                       // function executed by the thread
        while (!finished) {
            this_thread::sleep_for(chrono::milliseconds(1000));   
            cout << "\rLoading" << setw(++n) << setfill('.') << " "; 
        }
    }
    void terminate() {                                  // tell the thread/bar to stop 
        finished = true;
        if (t.joinable())
            t.join(); 
    }
};

You may then use this class in your code:

progress_bar bar;
for (long i = 0; i < 3000000000L; i++);
bar.terminate();    // you can have a delay up to 1 s 

The display is primitive: the \r make the display restart at the begin of current line. This works as long as you don't output anything else, and you have no more dots to display than length of line.

Alternatively, you can combine this with the curse answer, to write status to a fixed screen location more reliably.

Upvotes: 1

Aditya Kumar Praharaj
Aditya Kumar Praharaj

Reputation: 309

Ncurses library (though is ancient) is capable of emulating what you just said.

Upvotes: 0

Related Questions