16

I am trying to write the time on the same line instead of it stacking the outputs. I can not seem to get it to work though.

Here is what I have: I thought the "\r" would make it reprint on the same line, but this doesn't work. And I also tried printf("\r"); and that didn't work either.

Can anyone help me figure out how to get this to work?

void countdown(int time)
{
    int h = (time / 3600);
    int m = (time / 60) - (h * 60);
    int s = time % 60;

    std::stringstream ss;
    ss << h << ":" << m << ":" << s;
    std::string string = ss.str();

    cout << "\r" << string << endl;
}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
Zach Starnes
  • 3,108
  • 9
  • 39
  • 63
  • 3
    Have you tried just cout << h << ":" << m << ":" << s << endl; ? – Inertiatic Feb 19 '14 at 03:50
  • 1
    You are calling `countdown(...)` multiple times, and want all the times to appear on a single line? Is that the issue? – Ozraptor Feb 19 '14 at 03:53
  • 1
    possible duplicate of [Rewinding std::cout to go back to the beginning of a line](http://stackoverflow.com/questions/3057977/rewinding-stdcout-to-go-back-to-the-beginning-of-a-line) – kiranpradeep Jun 12 '15 at 08:51

4 Answers4

22
cout << "\r" << string << endl;

endl moves the cursor to the next line. Try replacing it with std::flush which just ensures output's sent towards the terminal. (You should also #include <iomanip> and use std::setw(2) / std::setfill('0') to ensure the text you display is constant width, otherwise say the time moves from:

23:59:59

to

0:0:0

The trailing ":59" from the earlier time is not currently being overwritten or cleared (you could write a few spaces or send a clear-to-end-of-line character sequence if your terminal has one, but fixed-width makes more sense).

So ultimately:

std::cout << '\r'
          << std::setw(2) << std::setfill('0') << h << ':'
          << std::setw(2) << m << ':'
          << std::setw(2) << s << std::flush;
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
5

try this:

cout << "\r" << string;

endl inserts a new-line character and flushes the stream.

Falko
  • 17,076
  • 13
  • 60
  • 105
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

endl inserts a new-line character and flushes the stream.

cout << "\r" << string ; //works
ForceBru
  • 43,482
  • 10
  • 63
  • 98
michaeltang
  • 2,850
  • 15
  • 18
1

I want to provide some useful information first.

You are inserting std::endl which prints next string on the next line.

std::endl is a newline \n followed by std::flush

The following newline \n and std::flush is equivalent to std::endl.

std::cout << printFunction() << '\n' << std::flush;

is just like

std::cout << printFunction() << std::endl;

Now removing std::endl will print the string in the same line.

cout << "\r" << string;
knoxgon
  • 1,070
  • 2
  • 15
  • 31