PDA

View Full Version : Updating one part of the output (C++ / Cout)



last2kn0
7th October 2007, 06:15
I was just wondering how some programs update certain parts of the terminal output.... Like when showing the percentage done. Its hard to explain...

Like if the output was this:

Percentage: [number]
Where [number] was continuously updated.

How is that done?:confused:

Thanks

daracne
7th October 2007, 07:26
This code will do what you're asking for, however, I have only tested it in windows. Its behavior may be different under linux/mac.



#include <iostream>
using std::iostream;

int main()
{
for (int i=0; i < 5; i++)
cout << "Progress: " << i*25 << "%\r";

return 0;
}

wysota
7th October 2007, 12:40
Shouldn't it be:

cout << "\rProgress: " << i*25 << "%";
?

I guess the difference is minimal... Oh, and don't forget to flush the output or you'll see nothing.

Michiel
7th October 2007, 13:10
For completions sake:


#include <iostream>
using namespace std;

int main() {
for (uint i = 0; i <= 100; ++i) {
cout << "\rProgress: " << i << "%" << flush;
for (uint j = 0; j < 9999999; ++j); // pause
}

cout << endl;

return 0;
}

\r means carriage return. Without a \n, it just takes the cursor back to the beginning of the current line. flush flushes the buffer.

last2kn0
7th October 2007, 21:25
Alright, thanks all.... Its nice to fill in one of those little gaps of knowledge. :)