views:

2579

answers:

5

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).

A: 

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);
}
srand
+11  A: 

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.

coppro
+1  A: 

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
}
Adam Pierce
That quite simply does not work. \f is a form feed; it does not clear the screen.
coppro
No, but it does clear the current printer page :-).
paxdiablo
+6  A: 

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,

fmsf
found that here http://www.daniweb.com/forums/thread95284.html
fmsf
+3  A: 

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.

Nicola Bonelli
To be clear:<ESC>[H moves the cursor to the top-left of the screen<ESC>[2J erases the screenAnyone wanting more details should Google "ANSI escape sequences".
Stéphane