126

As in the title. How can I clear console in C++?

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Thomas B
  • 1,289
  • 2
  • 9
  • 5
  • 1
    On what OS? It's quite a bit different on Linux vs. Windows, just for one example. If you want it for Windows, see: http://stackoverflow.com/questions/5866529/how-do-we-clear-the-console-in-assembly/5866648#5866648 – Jerry Coffin Jun 26 '11 at 19:48
  • Are you trying to print a bunch of lines and then clear it, or clear it after each line? – jpm Jun 26 '11 at 19:48
  • 1
    I want to reset console view sometimes. I dont want to spam console with million of newlines. – Thomas B Jun 26 '11 at 19:49
  • I asked [how to do this](https://stackoverflow.com/questions/20777191/how-do-i-clear-a-win32-cmd-console-window-without-using-system-in-c) in C, using a console window handle. [This is the answer](https://stackoverflow.com/a/20777329/2225787) I received. Hopefully, it helps with your case. – Agi Hammerthief Aug 07 '17 at 08:03

20 Answers20

82

For pure C++

You can't. C++ doesn't even have the concept of a console.

The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.

See this entry in the comp.lang.c++ FAQ:

OS-Specific

If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.

For Windows (as in your tag), check out this link:

Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.

Libraries (somewhat portable)

ncurses is a library that supports console manipulation:

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
65

For Windows, via Console API:

void clear() {
    COORD topLeft  = { 0, 0 };
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO screen;
    DWORD written;

    GetConsoleScreenBufferInfo(console, &screen);
    FillConsoleOutputCharacterA(
        console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    FillConsoleOutputAttribute(
        console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
        screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    SetConsoleCursorPosition(console, topLeft);
}

It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.

For *nixes, you usually can go with ANSI escape codes, so it'd be:

void clear() {
    // CSI[2J clears screen, CSI[H moves the cursor to top-left corner
    std::cout << "\x1B[2J\x1B[H";
}

Using system for this is just ugly.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 9
    "Using system for this is just ugly." - Why? Sure looks cleaner to me :) – Merlyn Morgan-Graham Jun 27 '11 at 07:05
  • 23
    @MerlynMorgan-Graham: It spawns a shell process to clear a friggin' console. In what way is that a clean solution? :P It's like using `echo` via `system()` instead of writing to stdout. – Cat Plus Plus Jun 27 '11 at 08:57
  • 2
    One liner FTW! ;) Yes, I'm being facetious. The fact that it spawns a shell process is good info for your answer, tho. +1 for the *nix version. – Merlyn Morgan-Graham Jun 27 '11 at 09:07
  • 8
    [Using `system()` is a common mistake.](http://homepage.ntlworld.com./jonathan.deboynepollard/FGA/clearing-the-tui-screen.html#CLS) [So, too, is your suggested method for Unices.](http://homepage.ntlworld.com./jonathan.deboynepollard/FGA/clearing-the-tui-screen.html#ANSI) [This is what one should do on POSIX systems.](http://homepage.ntlworld.com./jonathan.deboynepollard/FGA/clearing-the-tui-screen.html#POSIX) You got the Win32 part right, albeit that you didn't incorporate the "scroll back" convention. – JdeBP Jun 27 '11 at 14:48
  • 1
    @JdeBP your link is dead. Here's an [archive link](https://web.archive.org/web/20110414123447/http://homepage.ntlworld.com./jonathan.deboynepollard/FGA/clearing-the-tui-screen.html) – user2445507 Apr 17 '17 at 17:47
43

The easiest way for me without having to reinvent the wheel.

void Clear()
{
#if defined _WIN32
    system("cls");
    //clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
    //std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences 
#elif defined (__APPLE__)
    system("clear");
#endif
}
  • On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
  • On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
    std::cout<< u8"\033[2J\033[1;1H"; 
  • On MacOS Investigating...
Joma
  • 3,520
  • 1
  • 29
  • 32
37

For Linux/Unix and maybe some others but not for Windows before 10 TH2:

printf("\033c");

will reset terminal.

NoAngel
  • 1,072
  • 2
  • 18
  • 27
10

outputting multiple lines to window console is useless..it just adds empty lines to it. sadly, way is windows specific and involves either conio.h (and clrscr() may not exist, that's not a standard header either) or Win API method

#include <windows.h>

void ClearScreen()
  {
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
  }

For POSIX system it's way simpler, you may use ncurses or terminal functions

#include <unistd.h>
#include <term.h>

void ClearScreen()
  {
  if (!cur_term)
    {
    int result;
    setupterm( NULL, STDOUT_FILENO, &result );
    if (result <= 0) return;
    }

  putp( tigetstr( "clear" ) );
  }
Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
5
// #define _WIN32_WINNT 0x0500     // windows >= 2000 
#include <windows.h> 
#include <iostream>

using namespace std; 

void pos(short C, short R)
{
    COORD xy ;
    xy.X = C ;
    xy.Y = R ;
    SetConsoleCursorPosition( 
    GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void cls( )
{
    pos(0,0);
    for(int j=0;j<100;j++)
    cout << string(100, ' ');
    pos(0,0);
} 

int main( void )
{
    // write somthing and wait 
    for(int j=0;j<100;j++)
    cout << string(10, 'a');
    cout << "\n\npress any key to cls... ";
    cin.get();

    // clean the screen
    cls();

    return 0;
}
Firefox_
  • 61
  • 1
  • 1
4

To clear the screen you will first need to include the following header:

#include <stdlib.h>

this will import windows commands. Then you can use the 'system' function to run Batch commands (which edit the console). On Windows in C++, the command to clear the screen would be:

system("CLS");

And that would clear the console. The entire code would look like this:

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
system("CLS");
}

And that's all you need! Goodluck :)

Community
  • 1
  • 1
user3179329
  • 89
  • 1
  • 1
  • 3
    system("cls") is not a portable solution to this issue, however it does work on Windows systems. – CMS_95 Sep 29 '15 at 19:52
  • 5
    That is not a "module". C++ does not have "modules". Furthermore, `stdlib.h` is specified by the C standard, and has nothing to do with "importing windows commands" nor indeed Windows itself. Other than that nitpicking, you're fine. – Lightness Races in Orbit Oct 19 '15 at 23:13
3

In Windows:

#include <cstdlib>

int main() { 
    std::system("cls");
    return 0;
}

In Linux/Unix:

#include <cstdlib>

int main() { 
    std::system("clear");
    return 0;
}
pmttavara
  • 698
  • 7
  • 16
LoveToCode
  • 296
  • 2
  • 18
3

This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.

void clearScreen(){
    int clear = 5;
    do {
        cout << endl;
        clear -= 1;
    } while (clear !=0);
}
Max Goddard
  • 77
  • 1
  • 3
  • 11
2

Use system("cls") to clear the screen:

#include <stdlib.h>

int main(void)
{
    system("cls");
    return 0;
}
nateyolles
  • 1,851
  • 5
  • 17
  • 23
Wesam
  • 932
  • 3
  • 15
  • 27
2

In Windows we have multiple options :

  1. clrscr() (Header File : conio.h)

  2. system("cls") (Header File : stdlib.h)

In Linux, use system("clear") (Header File : stdlib.h)

1

If you're on Windows:

HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
    v5.Right = v6.dwSize.X;
    v5.Bottom = v6.dwSize.Y;
    v3.Char.UnicodeChar = 32;
    v4.Y = -v6.dwSize.Y;
    v3.Attributes = v6.wAttributes;
    v4.X = 0;
    *(DWORD *)&v5.Left = 0;
    ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
    v6.dwCursorPosition = { 0 };
    HANDLE v1 = GetStdHandle(0xFFFFFFF5);
    SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}

This is what the system("cls"); does without having to create a process to do it.

1

Works really well:

#include <windows.h>

void clearscreen()
{
    HANDLE hOut;
    COORD Position;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    Position.X = 0;
    Position.Y = 0;
    SetConsoleCursorPosition(hOut, Position);
}
Limtis
  • 95
  • 7
1

I'm using windows 10 terminal.

std::system("cls"); // cls or clear
ASMCoder
  • 33
  • 6
0

Here is a simple way to do it:

#include <iostream>

using namespace std;

int main()
{
    cout.flush(); // Flush the output stream
    system("clear"); // Clear the console with the "system" function
}
0

I don't that it is a good practice to use system commands (system("");) for these specific tasks so I made a function for clearing the console screen in C/C++ and it pretty much does the exact same functionality of the system("cls"); but just without calling a system command. (It is for Windows) you can copy this function to your C/C++ code so you can use this function to clear the console screen but check that Windows.h library is included in your code. Here is the code:

void clrscr() {
    DWORD Unused = 0;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    COORD zerozeroc = {0, 0};
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    DWORD Length = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacterW(GetStdHandle(STD_OUTPUT_HANDLE), ' ', Length, zerozeroc, &Unused);
    FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), csbi.wAttributes, Length, zerozeroc, &Unused);
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), zerozeroc);
}
Negai
  • 13
  • 5
  • Hello! Please edit to explain how this solves the question in a different or better way than the 2nd most voted answer, which is pretty much an identical function. – Edward Aug 22 '23 at 19:31
-1

Use System::Console::Clear();

This will clear (empty) the buffer

-1
#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish

}

The just call cls() anywhere

jdb_jdb
  • 19
-4

use: clrscr();

#include <iostream>
using namespace std;
int main()
      {           
         clrscr();
         cout << "Hello World!" << endl;
         return 0;
      }
vijay
  • 1
  • 1
  • 3
    "It used to be a function in , in old Borland C compilers. It's not a C++ standard function." http://stackoverflow.com/a/930141/1058115 – cojack Nov 19 '16 at 21:24
-8

The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.

int main(int argc, char *argv)
{
  for(int i = 0; i <1024*1024; i++)
      std::cout << ' ' << std::endl;

  return 0;
}

The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.

graphitemaster
  • 3,483
  • 4
  • 19
  • 14
  • 2
    This answer is [a common mistake](http://homepage.ntlworld.com./jonathan.deboynepollard/FGA/clearing-the-tui-screen.html#ANSI). – JdeBP Jun 27 '11 at 14:41