在 Linux C 中清除终端程序的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17006262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:10:29  来源:igfitidea点击:

Clearing output of a terminal program in Linux C

clinuxunixterminalclear

提问by Nathaniel Jobs

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

我想清除用 printf 语句生成的 C 程序的输出。我只想清除一行,例如:

[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.

我将在“DDDDDDDDDDDDDD”行中写入其他字符串。我只想把上面的 A、B、C 句留下。只清除D句改变其他句,无条件输出D句。

How do I do this?

我该怎么做呢?

采纳答案by Naruil

There're several ways to delete the DDDDDDDDDDDDDD

有几种方法可以删除 DDDDDDDDDDDDDD

  1. Print backspace several times
  1. 多次打印退格
printf("\b");
  1. Print carriage-return and then print something to override the original line
  1. 打印回车,然后打印一些东西来覆盖原来的行
printf("\r");
  1. If you are in a newline. You may use terminal commands to move your cursor
  1. 如果您在换行符中。您可以使用终端命令来移动光标

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

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

Other commands:

其他命令:

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

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

这是在终端中控制确切布局和格式的最佳方法

回答by kandelvijaya

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.

如果您不想在终端中显示,请注释最后一行或删除。printf("xxxx") 是用于在终端打印输出的语句。

回答by someone

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

如果您使用的是 X-Term 兼容软件(包括 Gnome 终端),请打印以下内容

printf("3[2J");

or

或者

cout << "3[2J";

where \033is the escape character in ASCIIand [2Jis the specific action (clear).

哪里\033ASCII 中的转义字符,[2J是具体操作(清除)。