How do I clear the console in BOTH Windows and Linux using C++ How do I clear the console in BOTH Windows and Linux using C++ windows windows

How do I clear the console in BOTH Windows and Linux using C++


There is no generic command to clear the console on both platforms.

#include <cstdlib>void clear_screen(){#ifdef WINDOWS    std::system("cls");#else    // Assume POSIX    std::system ("clear");#endif}


Short answer: you can't.

Longer answer: Use a curses library (ncurses on Unix, pdcurses on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows).

Most difficult answer: Use #ifdef _WIN32 and stuff like that to make your code act differently on different operating systems.


On linux it's possible to clear the console. The finest way is to write the following escape sequence to stdout:

write(1,"\E[H\E[2J",7);

which is what /usr/bin/clear does, without the overhead of creating another process.