48

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.

I found something that works, however, I'm not sure what it is or what it is doing.

cout << "\033[2J\033[1;1H";

That works but I have no clue what it is, if you could explain it, than I would much appreciate it.

Suraj Jain
  • 4,463
  • 28
  • 39
John
  • 491
  • 1
  • 4
  • 4

4 Answers4

69

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
14

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.

  • 1
    TERM environment variable not set. – Martin Pfeffer Nov 04 '15 at 17:10
  • 4
    Note that in C++, you need to `#include ` to use std::system. Also, although "clear" works on bash, for a Windows command line, you need "cls". – Mark Peschel Sep 06 '18 at 15:37
  • system() will fork(), then start a bash and then run the command. 1) You must avoid system() and 2) this doesn't answer the question where it was asked for C++ code and not about running a system's command. – reichhart Oct 20 '18 at 07:33
  • not portable anyway, clear does exactly same thing. You may not have access to clear in some cases. – Swift - Friday Pie Sep 12 '20 at 18:50
0

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

kauppi
  • 16,966
  • 4
  • 28
  • 19
0

you can write in a terminal "clear > data" and read in data the escapes sequance

0x1B[H0x1B[2J0x1B[3J

so

std::cout << "\033[H\033[2J\033[3J" ;