使用 C++ 代码清除 Linux 中的终端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4062045/
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
Clearing terminal in Linux with C++ code
提问by John
Okay, I have been researching on how to do this, but say I am running a program that has a whole bit of output on the terminal, how would I clear the screen from within my program so that I can keep my program running?
好的,我一直在研究如何做到这一点,但假设我正在运行一个在终端上有大量输出的程序,我将如何从我的程序中清除屏幕,以便我可以保持我的程序运行?
I know I can just type clear
in terminal and it clears it fine, but like I said, for this program it would be more beneficial for me.
我知道我可以clear
在终端中输入并清除它,但就像我说的那样,对于这个程序,它对我更有益。
I found something that works, however, I'm not sure what it is or what it is doing.
我发现了一些有用的东西,但是,我不确定它是什么或它在做什么。
cout << "3[2J3[1;1H";
That works but I have no clue what it is, if you could explain it, than I would much appreciate it.
那行得通,但我不知道它是什么,如果您能解释一下,我将不胜感激。
采纳答案by Marcelo Cantos
These are ANSI escape codes. The first one (\033[2J
) clears the entire screen (J
) from top to bottom (2
). The second code (\033[1;1H
) positions the cursor at row 1
, column 1
.
这些是 ANSI 转义码。第一个 ( \033[2J
)J
从上到下清除整个屏幕 ( ) ( 2
)。第二个代码 ( \033[1;1H
) 将光标定位在行1
、列1
。
All ANSI escapes begin with the sequence ESC[, have zero or more parameters delimited by ;, and end with a command letter (Jand Hin your case). \033
is the C-style octal sequence for the escape character.
所有ANSI转义开始序列ESC[,具有通过分隔零个或多个参数;,并用命令字母结束(J和H你的情况)。\033
是转义字符的 C 风格八进制序列。
See herefor the full roadshow.
请在此处查看完整的路演。
回答by Marcelo Cantos
Instead of depending on specific escape sequences that may break in unexpected situations (though accepting that trade-off is fine, if it's what you want), you can just do the same thing you'd do at your shell:
而不是依赖于可能在意外情况下中断的特定转义序列(尽管接受这种权衡是好的,如果这是你想要的),你可以做你在 shell 中做的同样的事情:
std::system("clear");
Though generally system() is to be avoided, for a user-interactive program neither the extra shell parsing nor process overhead is significant. There's no problem with shell escaping either, in this case.
尽管通常要避免使用 system(),但对于用户交互程序而言,额外的 shell 解析和进程开销都不重要。在这种情况下,shell 转义也没有问题。
You could always fork/exec to call clear if you did want to avoid system(). If you're already using [n]curses or another terminal library, use that.
如果你确实想避免 system(),你总是可以 fork/exec 调用 clear。如果您已经在使用 [n]curses 或其他终端库,请使用它。
回答by kauppi
For portability you should get the string from termcap's cl (clear) capability (Clear screen and cursor home). (Or use std::system("clear") as told by Roger Pate).
为了可移植性,您应该从 termcap 的 cl(清除)功能(清除屏幕和光标主页)中获取字符串。(或者按照 Roger Pate 的说法使用 std::system("clear") )。
man 3 termcap (in ncurses)
man 5 termcap
set | grep TERMCAP
man 3 termcap (in ncurses)
man 5 termcap
set | grep TERMCAP