Clearscreen statement!

I was hunting the web for a command to clear the screen and I found one!

It actually works too!
I know it works in Linux but I don't know about windows.

Anyway it's...

cout << "\x1b[2J\x1b[H" << flush;

Try it in your C++ scripts to clear the screen!
(Note: It doesn't actually clear the text it just moves it up so you can't see it.)




Source: http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/0f7e00f77b6b2dee
Last edited on
This seems to be a hot topic lately!

While the old VT100 escape sequence is common, it is unfortunately not much better than using
if (system("clear")) system( "cls" );
(I'll admit to using the VT100 escapes myself in schoolwork... I wrote a little include file that you can cout << clearscreen to do stuff... then I learned why it is bad...)

So other than the cool factor, I'd avoid it.

The reason is that not all terminals are created equal. Hence the ncurses terminfo library and putp() function. See my post in the following thread for an example of how to use it to clear the screen in _any_ terminal, without screwing up on things like old versions of dtterm and other oddball terminals/terminal emulators:

http://www.cplusplus.com/forum/beginner/387/

If you are on unix/linux, chances are that you already have ncurses installed.
If you are on windows, google "pdcurses".

Hope this helps.
Last edited on
Damn.
I thought I found one that was better than that system crap. :(
"Better" is a subjective word.

If by "better" you mean that it doesn't eat system resources or introduce security holes then yes, it is far and above better than that system crap. ;)
So I should use it until I get your's to work?
Absolutely. If you can deal with garbled output on some terminals.

In general, you should avoid things like 'clear' whenever possible. If you are writing a more advanced terminal application that makes use of fancy things like clearing the screen, changing colors, moving the cursor around, inserting and deleting lines and characters, getting non-buffered user input, etc. then you should be using the ncurses/pdcurses library directly and skip the standard I/O streams.

If all you want is to clear the screen now and again, which is fine and common, you might just want to reconsider if it is worth the trouble. Playing with the console alongside standard I/O opens a whole can of worms.

(I think it is fun though. I'm actually soon to submit a tutorial on how to do this kind of stuff correctly, since I notice that my system() trick is at the top of Google's "how do I clear the screen" hit list... and I don't want to be responsible for bad programming habits.)

Keep me updated with any problems you have, since I want to make this as workable as possible for as many people as possible...
Topic archived. No new replies allowed.