Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a console progress bar? (Windows)

So I have a function (or rather, I'll turn it into a function later) to make a random % progress in a console window; like this:

#include <iostream>
#include <time.h>
#include <cmath>
#include <windows.h>

using namespace std;

int main()
{
    srand(time(0));
    int x = 0;

    for(int i = 0; i<100; i++){
        int r = rand() % 1000;
        x++;
        cout << "\r" << x << "% completed." << flush;
        if(i < 43){
           Sleep(r/6);
        }else if(i > 43 && i < 74){
           Sleep(r/8);
        }else if(i < 98){
           Sleep(r/5);
        }else if(i > 97 && i != 99){
           Sleep(2000);
        }
    }

    cout << endl << endl << "Operation completed successfully.\n" << flush;
    return 0;
}

The thing is, I want the output to be like this:

1% completed

|

(later...)

25% completed

|||||||||||||||||||||||||

How can I do that?

Thanks in advance!

like image 884
Adam Avatar asked May 19 '13 14:05

Adam


1 Answers

Printing character '\r' is useful. It puts the cursor at the beginning of the line.

Since you can not access to previous line anymore, you can have something like this:

25% completed: ||||||||||||||||||

After each iteration:

int X;

...

std::cout << "\r" << percent << "% completed: ";

std::cout << std::string(X, '|');

std::cout.flush();

Also, you can use: Portable text based console manipulator

like image 171
masoud Avatar answered Sep 20 '22 00:09

masoud