Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear console

As in the title. How can I clear console in C++?

like image 984
Thomas B Avatar asked Jun 26 '11 19:06

Thomas B


People also ask

Which code is used to clear the Consol?

In the above example, we have specified the Windows operating system and the command that is used to clear the console is cls. We can also use the following code in the above program: public final static void clearConsole()

How do you clear the console in C++?

To clear the screen in Visual C++, utilize the code: system("CLS"); The standard library header file <stdlib. h> is needed.


2 Answers

For pure C++

You can't. C++ doesn't even have the concept of a console.

The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.

See this entry in the comp.lang.c++ FAQ:

  • http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.20

OS-Specific

If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.

For Windows (as in your tag), check out this link:

  • How do we clear the console in assembly?

Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.

Libraries (somewhat portable)

ncurses is a library that supports console manipulation:

  • http://www.gnu.org/software/ncurses/ (runs on Posix systems)
  • http://gnuwin32.sourceforge.net/packages/ncurses.htm (somewhat old Windows port)
like image 127
Merlyn Morgan-Graham Avatar answered Sep 30 '22 12:09

Merlyn Morgan-Graham


For Windows, via Console API:

void clear() {     COORD topLeft  = { 0, 0 };     HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);     CONSOLE_SCREEN_BUFFER_INFO screen;     DWORD written;      GetConsoleScreenBufferInfo(console, &screen);     FillConsoleOutputCharacterA(         console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written     );     FillConsoleOutputAttribute(         console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,         screen.dwSize.X * screen.dwSize.Y, topLeft, &written     );     SetConsoleCursorPosition(console, topLeft); } 

It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.

For *nixes, you usually can go with ANSI escape codes, so it'd be:

void clear() {     // CSI[2J clears screen, CSI[H moves the cursor to top-left corner     std::cout << "\x1B[2J\x1B[H"; } 

Using system for this is just ugly.

like image 34
Cat Plus Plus Avatar answered Sep 30 '22 14:09

Cat Plus Plus