How to create a command-line progress bar in C/C++
The task is to write a C/C++ program to draw a command-line progress bar.
Approach: To create a progress bar the idea is to use system() function which will give colored output. Below is the illustration of how to use system() function.
The system function accepts the following parameters for colouring the output screen:
- keyword: color
- Background color
- Foreground color
Color Codes:
Color | Color Code |
---|---|
BLACK | 0 |
BLUE | 1 |
GREEN | 2 |
CYAN | 3 |
RED | 4 |
MAGENTA | 5 |
BROWN | 6 |
LIGHT GRAY | 7 |
DARK GRAY | 8 |
LIGHT BLUE | 9 |
LIGHT GREEN | 10 |
LIGHT CYAN | 11 |
LIGHT RED | 12 |
LIGHT MAGENTA | 13 |
YELLOW | 14 |
WHITE | 15 |
BRIGHT GREEN | A |
BRIGHT CYAN | B |
BRIGHT RED | C |
BRIGHT MAGENTA | D |
BRIGHT YELLOW | E |
WHITE | F |
Syntax:
system(“color 9F”);
The above code will give White Color output with Bright Blue color on Background.
Below is the program to draw the progress bar in the command line in C/C++:
C
// C program to create loading bar #include <stdio.h> #include <windows.h> // Function to creating loading bar void loadingBar() { // 0 - black background, // A - Green Foreground system ( "color 0A" ); // Initialize char for printing // loading bar char a = 177, b = 219; printf ( "\n\n\n\n" ); printf ( "\n\n\n\n\t\t\t\t\t" + "Loading...\n\n" ); printf ( "\t\t\t\t\t" ); // Print initial loading bar for ( int i = 0; i < 26; i++) printf ( "%c" , a); // Set the cursor again starting // point of loading bar printf ( "\r" ); printf ( "\t\t\t\t\t" ); // Print loading bar progress for ( int i = 0; i < 26; i++) { printf ( "%c" , b); // Sleep for 1 second Sleep(1000); } } // Driver Code int main() { // Function Call loadingBar(); return 0; } |
C++
// C++ program to create loading bar #include <iostream> #include <windows.h> using namespace std; // Function to creating loading bar void loadingBar() { // 0 - black background, // A - Green Foreground system ( "color 0A" ); // Initialize char for printing // loading bar char a = 177, b = 219; printf ( "\n\n\n\n" ); printf ( "\n\n\n\n\t\t\t\t\t" + "Loading...\n\n" ); printf ( "\t\t\t\t\t" ); // Print initial loading bar for ( int i = 0; i < 26; i++) printf ( "%c" , a); // Set the cursor again starting // point of loading bar printf ( "\r" ); printf ( "\t\t\t\t\t" ); // Print loading bar progress for ( int i = 0; i < 26; i++) { printf ( "%c" , b); // Sleep for 1 second Sleep(1000); } } // Driver Code int main() { // Function Call loadingBar(); return 0; } |
Output:
Below is the output of the above program:
Please Login to comment...