Clearing terminal in Linux with C++ code

后端 未结 3 1084
粉色の甜心
粉色の甜心 2020-11-28 05:31

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 p

相关标签:
3条回答
  • 2020-11-28 06:03

    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.

    All ANSI escapes begin with the sequence ESC[, have zero or more parameters delimited by ;, and end with a command letter (J and H in your case). \033 is the C-style octal sequence for the escape character.

    See here for the full roadshow.

    0 讨论(0)
  • 2020-11-28 06:12

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

    man 3 termcap (in ncurses)
    man 5 termcap
    set | grep TERMCAP

    0 讨论(0)
  • 2020-11-28 06:21

    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:

    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.

    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.

    0 讨论(0)
提交回复
热议问题