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

13

28

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

Tachistoscope answered 23/10, 2008 at 5:23 Comment(1)
The console does not even exist in standard C++11, so pedantically your question does not even make any sense. And what about your program foo being redirected (e.g. foo > output.txt) or pipelined (e.g. foo | grep xxx) ? BTW, some computers don't have any consoles (e.g. most web servers or VPS)Benildis
P
29

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.

Pul answered 23/10, 2008 at 5:23 Comment(0)
E
63

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
}
Estipulate answered 23/10, 2008 at 5:23 Comment(3)
This is the most concise, general-purpose answer that will work in 99% of all cases. Should be the accepted answer.Lodger
cplusplus.com/articles/j3wTURfi According to this, system() should not be in use...Dupleix
@Estipulate What Would You Say About This Answer https://mcmap.net/q/485959/-how-do-i-clear-the-console-in-both-windows-and-linux-using-c?Annelieseannelise
P
29

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.

Pul answered 23/10, 2008 at 5:23 Comment(0)
S
13

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.

Scrivenor answered 23/10, 2008 at 5:23 Comment(3)
To be clear: <ESC>[H moves the cursor to the top-left of the screen <ESC>[2J erases the screen Anyone wanting more details should Google "ANSI escape sequences".Dagley
This only works for Linux terminals that support ANSI-compatible escape sequences.Marquettamarquette
error: no matching function for call to 'write' write(1,"\E[H\E[2J",7); // we use ANSI escape sequences here. ^~~~~ And I did the includes and checked the namespace.Manque
B
12

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);
//....
Burnell answered 23/10, 2008 at 5:23 Comment(0)
D
9

Short answer

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

Long answer, please read:

system("pause") clarification

Dampproof answered 23/10, 2008 at 5:23 Comment(0)
J
4

The question as posted is unanswerable, because it imposes impossible restrictions. "Clearing the screen" is a very different action across different operating systems, and how one does it is operating system specific. See this Frequently Given Answer for a full explanation of how to do it on several popular platforms with "consoles" and platforms with "terminals". You'll also find in the same place some explanation of the common mistakes to avoid, several of which are — alas! — given above as answers.

Jammiejammin answered 23/10, 2008 at 5:23 Comment(0)
M
3

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
}
Marcasite answered 23/10, 2008 at 5:23 Comment(1)
That quite simply does not work. \f is a form feed; it does not clear the screen.Pul
F
2

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);
}
Flicker answered 23/10, 2008 at 5:23 Comment(0)
H
1

As others have already said, there's no way to have one identical piece of code that clears the console on both Windows and Linux.

I'll also strongly recommend against using std::system:

  • it makes your program vulnerable to attacks; what if someone replaced clear/cls with their own malicious program
  • as a consequence of the above, antivirus programs hate std::system. If your code uses it, the resulting binary may test positive for virus even if it's meant to be harmless. (Note that it is not actually harmless.)

Here's my solution:

#ifdef _WIN32
#include <Windows.h>
#endif

void clrscr() {
#ifdef _WIN32
    COORD tl = { 0,0 };
    CONSOLE_SCREEN_BUFFER_INFO s;
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(console, &s);
    DWORD written, cells = s.dwSize.X * s.dwSize.Y;
    FillConsoleOutputCharacter(console, ' ', cells, tl, &written);
    FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
    SetConsoleCursorPosition(console, tl);
#else
    std::cout << "\033[2J\033[1; 1H";
#endif
}

You may follow the pattern shown above, and change the two code segments anyway you like.

Hexastyle answered 23/10, 2008 at 5:23 Comment(0)
B
1

This code clears the console in BOTH Windows and Unix (Although it's actually compiled differently):

// File: clear_screen.h
#ifndef _CLEAR_SCREEN_H
#define _CLEAR_SCREEN_H
void clearScreen(void); /* Clears the screen */
#endif /* _CLEAR_SCREEN_H */
// File: clear_screen.c
#ifdef _WIN32
#include <windows.h>
void clearScreen(void) {
    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD topLeft = {0, 0};
    DWORD dwCount, dwSize;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hOutput, &csbi);
    dwSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(hOutput, 0x20, dwSize, topLeft, &dwCount);
    FillConsoleOutputAttribute(hOutput, 0x07, dwSize, topLeft, &dwCount);
    SetConsoleCursorPosition(hOutput, topLeft);
}
#endif /* _WIN32 */

#ifdef __unix__
#include <stdio.h>
void clearScreen(void) {
    printf("\x1B[2J");
}
#endif /* __unix__ */
Boettcher answered 23/10, 2008 at 5:23 Comment(0)
C
1

Well there is a very close alternative to clearing the screen. You could try using a for loop that repeats new lines a lot. For example:

for (i = 0; i < 100000; i++)
{
  printf ("\n\n\n\n\n");
}

After you do this loop the terminal wan't allow you to scroll back to where you were at the top, an unprofessional approach with common sense pretty much. It does not directly answer what you are asking but it can work.

Clarion answered 23/10, 2008 at 5:23 Comment(2)
@leonardo_assumpcao 10³³³³³³³³³³Milch
Seems enough for my 5.874 km wide monitorAstri
S
-2

Wouldn't

for (int i=0;i<1000;i++){cout<<endl;}

clear the screen in all OSes?

Sigfrid answered 23/10, 2008 at 5:23 Comment(0)
L
-4

This should work if you're working on console

#include <conio.h>

int main()

{
    clrscr();
}
Lavernlaverna answered 23/10, 2008 at 5:23 Comment(4)
< conio.h > is not part of c++ standard, it will only work in TurboC++Morbific
but not all compilers, just a few. Are there any conio.h on LINUX, which is what the OP cares? #8792817Descendible
and your code can't even compile on Windows/MSDOS, before I edited itDescendible
conio.h is very old deprecated library for 16-bit compilers toady in modern systems this should not be recommended.Engdahl

© 2022 - 2024 — McMap. All rights reserved.