How can I clear console How can I clear console windows windows

How can I clear console


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.


For Linux/Unix and maybe some others but not for Windows before 10 TH2:

printf("\033c");

will reset terminal.