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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With