I made a simple progress bar with percentage counter for console applications in C++. Below is my code:
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cmath>
void show_progress_bar(int time, const std::string &message, char symbol)
{
std::string progress_bar;
const double progress_level = 1.42;
std::cout << message;message << "\n\n";
for (double percentage = 0; percentage <= 100; percentage += progress_level)
{
progress_bar.insert(0, 1, symbol);
std::cout << "\r [" << std::ceil(percentage) << '%' << "] " << progress_bar;
std::this_thread::sleep_for(std::chrono::milliseconds(time));
}
std::cout << "\n\n";
}
Some explanation about my code. I've used three parameters in order to make a header called "progress_bar.h", so whenever I need to use in my programs I can change the time of the display of the progress bar, the message used, for example "Loading..."
, "Generating report..."
, etc, and also the symbol. Sometimes I've used a simple '*'
, other times I've used the character with ASCII code 254 (it's a black square). So, basically my idea was to have a general progress bar in order to be used whenever I need, and in different ways.
On the other hand, the variable progress_level
has the value given above in order to prevent the progress bar for jumping to the next line (which was an ugly thing). That made to change the variable percentage
to a double
type. To be able to print integer values I've used the ceil
function.
My questions:
How good is in general my progress bar? What can be changed in order to make look my code cleaner?
Is there a simpler (better) way of using strings in order to make a progress bar like the above (i.e. showing a percentage counter)? (I know of other ways to make progress bars, but I'm mostly interested in ones using strings).