How can I clear console

328,175

Solution 1

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:

Solution 2

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.

Solution 3

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

printf("\033c");

will reset terminal.

Solution 4

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

Solution 5

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" ) );
  }
Share:
328,175

Related videos on Youtube

Thomas B
Author by

Thomas B

Updated on July 08, 2022

Comments

  • Thomas B
    Thomas B almost 2 years

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

    • Jerry Coffin
      Jerry Coffin almost 13 years
      On what OS? It's quite a bit different on Linux vs. Windows, just for one example. If you want it for Windows, see: stackoverflow.com/questions/5866529/…
    • Thomas B
      Thomas B almost 13 years
      I want to reset console view sometimes. I dont want to spam console with million of newlines.
  • Merlyn Morgan-Graham
    Merlyn Morgan-Graham almost 13 years
    "Using system for this is just ugly." - Why? Sure looks cleaner to me :)
  • Cat Plus Plus
    Cat Plus Plus almost 13 years
    @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.
  • Merlyn Morgan-Graham
    Merlyn Morgan-Graham almost 13 years
    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.
  • JdeBP
    JdeBP almost 13 years
    Using system() is a common mistake. So, too, is your suggested method for Unices. This is what one should do on POSIX systems. You got the Win32 part right, albeit that you didn't incorporate the "scroll back" convention.
  • LoveToCode
    LoveToCode almost 9 years
    [Error] 'System ' has not been declared.
  • CMS_95
    CMS_95 over 8 years
    system("cls") is not a portable solution to this issue, however it does work on Windows systems.
  • Lightness Races in Orbit
    Lightness Races in Orbit over 8 years
    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.
  • FryGuy
    FryGuy over 8 years
    This is for c++/CLI (aka .NET c++)
  • Dialecticus
    Dialecticus almost 8 years
    Already mentioned in the accepted answer. No new information here.
  • cojack
    cojack over 7 years
    "It used to be a function in <conio.h>, in old Borland C compilers. It's not a C++ standard function." stackoverflow.com/a/930141/1058115
  • user2445507
    user2445507 about 7 years
    @JdeBP your link is dead. Here's an archive link
  • JdeBP
    JdeBP almost 7 years
    No need for archives. jdebp.eu./FGA/clearing-the-tui-screen.html#CLS exists.
  • Nathan Smiechowski
    Nathan Smiechowski almost 7 years
    Then get rid of cout/wcout and simply pipe stuff to system("echo " + your output);
  • Agi Hammerthief
    Agi Hammerthief almost 7 years
    This isn't what the OP is looking for. Read the comment added to the question.
  • John Doe
    John Doe over 4 years
    Note that any call to system() could be a security issue.
  • HolyBlackCat
    HolyBlackCat almost 3 years
    This was already suggested in several other answers.