Progress Bar in the Terminal with Just iostream
Progress Bar in the Terminal with Just iostream
Content
#include <iostream>
#include <thread>
#include <chrono>
int main() {
const int totalSteps = 100;
for (int i = 0; i <= totalSteps; ++i) {
std::cout << "\r[" << std::string(i, '=') << std::string(totalSteps - i, ' ') << "] " << i << "%";
std::cout.flush();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
std::cout << "\nDone!" << std::endl;
return 0;
}
In this example, we define a `totalSteps` variable to represent the total number of steps in our progress bar. We then use a loop to update the progress bar by printing it to the console. The `std::string(i, '=')` creates a string of '=' characters representing the completed portion of the bar, and `std::string(totalSteps - i, ' ')` creates a string of spaces for the remaining portion. The `\r` character is used to return the cursor to the beginning of the line so that the progress bar can be updated in place.
Conclusion
Creating a simple progress bar in the terminal using just `iostream` is straightforward and effective. By leveraging basic C++ constructs, you can provide visual feedback to users during long-running tasks. This method is lightweight and does not require any additional libraries, making it an ideal solution for many applications.