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

62,464

Solution 1

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.

Solution 2

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
}

Solution 3

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.

Solution 4

A simple trick: Why not checking the OS type by using macros in combination with using the system() command for clearing the console? This way, you are going to execute a system command with the appropriate console command as parameter.

#ifdef _WIN32
#define CLEAR "cls"
#else //In any other OS
#define CLEAR "clear"
#endif

//And in the point you want to clear the screen:
//....
system(CLEAR);
//....

Solution 5

Short answer

void cls(void)
{
    system("cls||clear");
    return;
}

Long answer, please read:

system("pause") clarification

Share:
62,464
worbel
Author by

worbel

(your about me is currently blank)

Updated on March 25, 2021

Comments

  • worbel
    worbel about 3 years

    I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).