C++ Progress Bar

Hello,……

One of the things that was always fascinated me was the implementation of Progress Bar with console applications.

If you ever used applications such as “wget” you know the progress bar is used to notify the user about the progress of the download or the process.

Here is the C++ source code of the Progress bar, it can also be used with C++14 threads if you application would have more than one thread.

 

#include <iostream>
#include <thread>
#include <chrono>

int main() {
	float progress = 0.0;

	std::cout << "This is checking progress bar." << std::endl;

	while (progress <= 1.0) {
		int barWidth = 50;

		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.2; // for demonstration only
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	}
	std::cout << std::endl;

	std::cout << "Task Completed :)" << std::endl;

	return 0;
}

And here is the output of the program.

Hope you find this useful.

Thanks.

— Saeed 🙂



BTC: 1G1myr8rYv7SgyYtyWXLu3WLSPNaHCGGcd

Comments are closed.