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).
I know this isn't answering my own question but!
This works for Windows (#include <windows.h>
):
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
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.
This is how you do it on any other platform but it doesn't work in Windows:
cout << "\f";
Perhaps you'll need to make a conditional compilation:
void clrscr()
{
#ifdef _WIN32
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ',
csbi.dwSize.X * csbi.dwSize.Y,
coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
#else
cout << "\f";
#endif
}
For c++
#include <cstdlib>
void clear_screen()
{
#ifdef WINDOWS
std::system ( "CLS" );
#else
// Assume POSIX
std::system ( "clear" );
#endif
}
There is no generic command to just clear the console in both languages,
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.