As in the title. How can I clear console in C++?
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()
To clear the screen in Visual C++, utilize the code: system("CLS"); The standard library header file <stdlib. h> is needed.
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:
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:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With