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
#include <stdio.h>
#include <windows.h>
void loadingBar()
{
system ( "color 0A" );
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" );
for ( int i = 0; i < 26; i++)
printf ( "%c" , a);
printf ( "\r" );
printf ( "\t\t\t\t\t" );
for ( int i = 0; i < 26; i++) {
printf ( "%c" , b);
Sleep(1000);
}
}
int main()
{
loadingBar();
return 0;
}
|
C++
#include <iostream>
#include <windows.h>
using namespace std;
void loadingBar()
{
system ( "color 0A" );
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" );
for ( int i = 0; i < 26; i++)
printf ( "%c" , a);
printf ( "\r" );
printf ( "\t\t\t\t\t" );
for ( int i = 0; i < 26; i++) {
printf ( "%c" , b);
Sleep(1000);
}
}
int main()
{
loadingBar();
return 0;
}
|
Output:
Below is the output of the above program:
Last Updated :
19 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...