Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rewrite a line of text in a console project? c++

Tags:

c++

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?

like image 818
user3797758 Avatar asked Nov 30 '22 00:11

user3797758


2 Answers

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.

like image 161
marsh Avatar answered Dec 05 '22 09:12

marsh


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.

like image 44
LoW Avatar answered Dec 05 '22 11:12

LoW