2

I want to clear the output of a C program produced with printf statements. I want to clear only one line, for example:

[source]

printf("AAAAAAAAAAAAAA\n");
printf("BBBBBBBBBBBBBB\n");
printf("CCCCCCCCCCCCCC\n");
printf("DDDDDDDDDDDDDD\n");

[terminal]

AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC
DDDDDDDDDDDDDD

[I hope]

AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC

I will "DDDDDDDDDDDDDD" line in write other string. I just want the above A, B, C sentences to left. Only clear D sentences to change the other sentences, unconditionally output D sentences.

How do I do this?

3 Answers 3

14

There're several ways to delete the DDDDDDDDDDDDDD

  1. Print backspace several times
printf("\b");
  1. Print carriage-return and then print something to override the original line
printf("\r");
  1. If you are in a newline. You may use terminal commands to move your cursor

such as printf("\033[8;5Hhello"); // Move to (8, 5) and output hello

Other commands:

printf("\033[XA"); // Move up X lines;
printf("\033[XB"); // Move down X lines;
printf("\033[XC"); // Move right X column;
printf("\033[XD"); // Move left X column;
printf("\033[2J"); // Clear screen
...
  1. Don't forget ncurses

It is the best ways to control the exact layout and format in a terminal

2
  • \033[8;5Habcd what's means? Jun 9, 2013 at 4:36
  • Move to (8,5) and output abcd. ;) In your case you should use printf("\033[1A") to move up one line.
    – Naruil
    Jun 9, 2013 at 4:40
2

If you are using X-Term compatibles (Gnome Terminal included), then print the following

printf("\033[2J");

or

cout << "\033[2J";

where \033 is the escape character in ASCII and [2J is the specific action (clear).

0

I tried answering for what is best expected here.

printf("AAAAAAAAAAAAAA");
printf("BBBBBBBBBBBBBB");
printf("CCCCCCCCCCCCCC");
//printf("DDDDDDDDDDDDDD");

comment the last line or delete if you dont want to display in terminal. printf("xxxx") is the statement used for printing output in terminal.

1
  • 1
    You completely missed the point. The point is not to get it to stop printing, it's to clear it from the terminal (like if you want to refresh the terminal view, etc)
    – Allison
    May 9, 2018 at 16:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.