program progress by displaying percentage

Hi,

I'm trying to incorporate a sort of progress bar in my program.
I thought this might be easily accomplished by printing on screen the percentage of the number of iteration my program has carried out. However I've stumbled upon an issue.

 
cout << (double) ( j / n * 100 ) << "%";


In the above simple line of code, I'm printing the percentile progress every iteration j of my program. This unfortunately does not overwrite the previous percentage displayed, so I get a succession of percentages. I can add a endl and then this will happen every line, but this is not what I want.

I would like the output of the above cout to overwrite the previous value, so that it looks like the percentile progress is updating itself.

Could someone help or point me in the right direction for this one?

Thanks

Andres
Try this:

1
2
3
4
5
for(int i=0; i<100; i++)
{
	cout<<(double) i <<"%";
	system("cls");
}
What you can do is to erase the previous string similar to this:

1
2
3
4
5
6
7
8
for (int i=0;i<=100;i++)
{
  const string statusStr=IntToStr(i)+"%";
  cout << statusStr << flush;  
  usleep(50000);
  cout << string(statusStr.length(),'\b');
}
cout << "Done." << endl;


You can also use ANSI escape codes:

1
2
3
4
5
for (int i=0;i<=100;i++)
{
  cout << "\x1B[s" << i << "%" << flush << "\x1B[u";
  usleep(50000);
}


But with that, you leave the standard C++ territory, as this is terminal-specific.
Topic archived. No new replies allowed.