Lessons, tips, and experiences from venturing through the realms of technology and software.

Monday, August 3, 2009

C++ Console Progress Bar

Given the percentage complete, the following piece of code can print a text progress bar for a console application along with an animatedly "spinning" slash to show that the program is still running.


// this function prints progress bar
// pre: percentage complete
// post: progress bar
void progressbar(int percent)
{
static stringstream bars;
static int x = 0;
string slash[4];
slash[0] = "\\";
slash[1] = "-";
slash[2] = "/";
slash[3] = "|";
bars << "|";
cout << "\r"; // carriage return back to beginning of line
cout << bars.str() << " " << slash[x] << " " << percent << " %"; // print the bars and percentage
x++; // increment to make the slash appear to rotate
if(x == 4)
x = 0; // reset slash animation
}


1 comment:

Anonymous said...

i cant get it work. please help.
here is my code:

--------------------------
main.cpp
--------------------------
#include
#include "progress.h"

int main()
{
progressbar(100);
return 0;
}

-----------------
progress.h
-----------------
#include
#include

using namespace std;

void progressbar(int percent)
{
static stringstream bars;
static int x = 0;
string slash[4];
slash[0] = "\\";
slash[1] = "-";
slash[2] = "/";
slash[3] = "|";
bars << "|";
cout << "\r"; // carriage return back to beginning of line
cout << bars.str() << " " << slash[x] << " " << percent << " %"; // print the bars and percentage
x++; // increment to make the slash appear to rotate
if(x == 4)
x = 0; // reset slash animation
}

This site is a Coconuter production