22

Possible Duplicate:
How to update a printed message in terminal without reprinting (Linux)

I have c++ code, performing some simulations.

I want to show the percentage of my simulation, but I don't want to output a new line every step, like

%1

%2

%3

...

Is there a way, in c++ or in shell scripts to show the progress without creating new lines?

Thanks

Edit 1

Anyone know how to update a number on my personal webpage without refreshing the whole page?

Thanks

Edit 2

double N=0;
forAll (internalIDs_, i) {
    N++;
    double percent = 100*N/internalIDs_.size();
    // Info<< "\rProgress: " << percent << "%" << endl;
    printf("\r[%6.4f%%]",percent);}

The terminal cursor keeps blinking cyclically through the numbers, very annoything, how to get rid of this?

Community
  • 1
  • 1
Daniel
  • 2,576
  • 7
  • 37
  • 51

2 Answers2

25

The trick used for this is to return to the first position in the current line instead of progressing to the next line.

This is done by writing the \r character (carriage return) to the terminal/stdout.

ypnos
  • 50,202
  • 14
  • 95
  • 141
  • 1
    Hmm, so I need to `fflush(stdout);`? – Daniel Jun 11 '12 at 18:22
  • 1
    Yes. Flushing is part of std::endl. As you don't use std::endl, you need to flush. In C++ you can flush with std::cout.flush(), or use std::cout << "\rtest" << std::flush; Caution: Flushing too often can severely degrade the performance of your application. E.g. if you output percentages, only update your output when the number is actually increased. – ypnos Jun 11 '12 at 18:32
  • Sorry to bother you again, I see the terminal cursor keeps blinking through the percentage numbers in a very fast way and cyclicly, what should I do to get rid of this.. – Daniel Jun 11 '12 at 19:02
  • As I said, less updates help. But it is hard to get rid of the cursor. It's a completely new topic. – ypnos Jun 11 '12 at 20:07
  • @ypnos How would I do this for multiple lines? Let's say I'd like to update values across 6 lines - 1 on each line. – DearVolt Sep 23 '15 at 14:40
  • 1
    @DJSquared There is no simple solution for this. You can put the terminal in a different mode to do things like a console UI etc., but it is more complicated. A popular library for this is `ncurses`, see https://en.wikipedia.org/wiki/Ncurses – ypnos Sep 23 '15 at 15:44
18
cout << "\r%1";
cout << "\r%2";
cout << "\r%3";

...

\r - move at the begin of line;

but! if :

cout << "\rsomelongmessage";
cout << "\rshort";

then you get at out:

shortongmessage

because of:

somelongmessage
^^^^^
short

but you can:

cout << "\rsomelongmessage";
cout << "\rshort          ";

then you get finally:

short
ScaV
  • 185
  • 1
  • 1
  • 7