Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo a newline (\n) printed to command line

Tags:

c++

c

stdout

printf("Error %d\n", 1);
printf("\nStatus: %d%%", 50);

prints

Error 1

Status: 50%

In this set up, is there any chance to insert Error 2\n between Error 1\n and \nStatus: 50%. I understand that \r and \b can be used to change printed text in the same line (e.g., if there is a single \n between Error 1 and Status: 50%), but can I change text in a previous line?

Thanks!

like image 704
st12 Avatar asked Dec 25 '10 17:12

st12


3 Answers

What @Ryan said.

Explanation why: stdout is some abstract stream that doesn't have to be the terminal. It may be a file, a pipe, a socket, a printer, a text to speech device or whatever. In many cases there is no sense to what you asked to do. Hence you need some library that works with the terminal specifically.

like image 57
Yakov Galka Avatar answered Nov 13 '22 11:11

Yakov Galka


Sorry, you cannot.

But you may issue system calls to clear the whole screen instead, like system("clear") (OS-dependent).

Or use ncurses just as Kos mentioned in the comment.

like image 41
Ryan Li Avatar answered Nov 13 '22 10:11

Ryan Li


You could use ANSI Escapesequences to move your "cursor" one line up:

void cursorOnLineUp(void) { printf("\033[1A"); }

Or set it to a specific position:

void setCursor(int column, int row) { printf("\033[%d;%dH", row, column) }

Haven't tried it for C++, but succesfully used it for a simple game in ANSI-C!

like image 33
Christoph Haefner Avatar answered Nov 13 '22 12:11

Christoph Haefner