5

I'm working on a c++ console project and i would like to show a percentage without making a new line each time (so that the window doesn't get clogged with thousands of lines).

Is there a way of removing the last line that was printed or something to say that the next time that i output a line it should replace the current line?

user3797758
  • 829
  • 1
  • 14
  • 28
  • There's many ways of doing this, but most of them are dependent on your host environment (i.e. operating system). What OS are you targeting? – Cameron Feb 05 '15 at 17:27
  • 1
    possible duplicate of [How can I erase the current line printed on console in C ? I am working on a linux system](http://stackoverflow.com/questions/1508490/how-can-i-erase-the-current-line-printed-on-console-in-c-i-am-working-on-a-lin) – inetknght Feb 05 '15 at 17:27
  • Even though that has the same answer in it, that is based around C whereas i was asking about C++. someone looking for a solution to this in C++ would't necessarily look at C based answers. – user3797758 Feb 05 '15 at 18:03

3 Answers3

17

You can use a \r (carriage return) to return the cursor to the beginning of the line:

This works on windows and Linux.

From: Erase the current printed console line

You could alternatively use a series of backspaces.

string str="Hello!";
cout << str;
cout << string(str.length(),'\b');
cout << "Hello again!";

From: http://www.cplusplus.com/forum/unices/25744/

Maybe mark as duplicate? I am really not sure how.

Community
  • 1
  • 1
marsh
  • 2,592
  • 5
  • 29
  • 53
6

A simple example that I tested on Linux would be:

std::cout << "Some text to display..." << "\t\r" << std::flush;

Here the \t adds a tabulation to handle slightly varying string lengths and \r sends the cursor back at the start of the line (as mentioned in other answers). std::flush is required to guarantee that the line is displayed without jumping to the next line.

LoW
  • 582
  • 7
  • 15
2

This is very platform-dependent and terminal-dependent. But, you may want to look at ncurses for a start: http://linux.die.net/man/3/ncurses

For Windows: How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?

For Linux: https://unix.stackexchange.com/questions/43075/how-to-change-the-contents-of-a-line-on-the-terminal-as-opposed-to-writing-a-new

Community
  • 1
  • 1
coderkevin
  • 359
  • 1
  • 5