Search code examples
c++windowsconsole-applicationcarriage-return

c++ Carriage Return Line Feed long string followed by a shorter string


I have an application which I want to print status messages with. However, sometimes it occurs that a shorter status message follows a longer status message, which leads to the following situation:

Long message:

this is the long status message which is longer than the short one

Shorter message:

This is the short status messagewhich is longer than the short one
//this one should end here      ^

The code I'm using is:

cout << StatusMessage << '\r';

How can I overcome this problem and firstly erase the whole line before printing the new line? Preferably with a cross platform solution, but for now I'm working on Windows

Note: I already tried to overwrite the line with \b or spaces, however this may result in a multiple line cleaning which removes the functionality of my \r approach.


Solution

  • I'd use '\b' (backspace) repeatedly in the length of the former output for your case. It seems to be pretty standardized:

    cout << StatusMessage << '\r';
    cout << std::string(StatusMessage.size(),'\b');