关于C ++:如何清除控制台

How can I clear console

如标题中所示。 如何清除C ++中的控制台?


对于纯C ++

你不能C ++甚至没有控制台的概念。

该程序可以将其打印到打印机,直接输出到文件或重定向到另一个程序的输入(无论它关心什么)。即使您可以清除C ++中的控制台,也会使这些情况更加混乱。

请参阅comp.lang.c ++常见问题解答中的此项:

  • http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.20

特定于操作系统

如果清除程序中的控制台仍然有意义,并且您对特定于操作系统的解决方案感兴趣,那么这些解决方案确实存在。

对于Windows(如标签中所示),请查看以下链接:

  • 我们如何在组装时清除控制台?

编辑:以前使用system("cls");提到了此答案,因为Microsoft表示这样做。但是,在评论中已指出,这样做不是安全的事情。由于此问题,我已删除了指向Microsoft文章的链接。

图书馆(有点可移植)

ncurses是一个支持控制台操作的库:

  • http://www.gnu.org/software/ncurses/(在Posix系统上运行)
  • http://gnuwin32.sourceforge.net/packages/ncurses.htm(有点旧的Windows端口)


对于Windows,通过控制台API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
}

它很乐意忽略所有可能的错误,但嘿,这是控制台清除。不像system("cls")可以更好地处理错误。

对于* nixes,通常可以使用ANSI转义码,因此它是:

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

为此使用system很难看。


对于Linux / Unix,也许还有其他一些,但不适用于Windows 10 TH2之前的Windows:

1
printf("\033c");

将重置终端。


向窗口控制台输出多行是没有用的..它只是向其中添加空行。
可悲的是,方法是特定于Windows的,并且涉及conio.h(和clrscr()可能不存在,也不是标准标头)或Win API方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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 );
  }

对于POSIX系统,它更简单,您可以使用ncurses或终端函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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" ) );
  }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// #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 <<"

press any key to cls..."
;
    cin.get();

    // clean the screen
    cls();

    return 0;
}

在Windows中:

1
2
3
4
5
6
#include <cstdlib>

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

在Linux / Unix中:

1
2
3
4
5
6
#include <cstdlib>

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


要清除屏幕,您首先需要包括一个模块:

1
#include <stdlib.h>

这将导入Windows命令。然后,您可以使用"系统"功能运行批处理命令(用于编辑控制台)。在Windows中,使用C ++,清除屏幕的命令为:

1
system("CLS");

这将清除控制台。整个代码如下所示:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <stdlib.h>

using namespace std;

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

这就是您所需要的!祝好运 :)


使用system("cls")清除屏幕:

1
2
3
4
5
6
7
#include <stdlib.h>

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


在MAC上很难做到这一点,因为它无法访问可帮助清除屏幕的Windows功能。我最好的解决方法是循环并添加行,直到清除终端,然后运行程序。但是,如果您主要且经常使用它,那么效率或内存友好性就不那么高。

1
2
3
4
5
6
7
void clearScreen(){
    int clear = 5;
    do {
        cout << endl;
        clear -= 1;
    } while (clear !=0);
}

对我而言,最简单的方法是无需重新发明轮子。

1
2
3
4
5
6
7
8
9
10
void Clear()
{
#if defined _WIN32
    system("cls");
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
#elif defined (__APPLE__)
    system("clear");
#endif
}

在Windows中,我们有多种选择:

  • clrscr()(头文件:conio.h)

  • system(" cls")(头文件:stdlib.h)

  • 在Linux中,使用system(" clear")(头文件:stdlib.h)


    这是一种简单的方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <iostream>

    using namespace std;

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <cstdlib>

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

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

    }

    只需在任何地方调用cls()


    使用系统:: Console :: Clear();

    这将清除(清空)缓冲区


    您可以通过system(")使用操作系统的清除控制台方法;
    对于Windows,它将是system(" cls");例如
    而不是针对不同的操作系统发布三个不同的代码。只需制定一种方法来获取正在运行的操作系统。
    您可以通过检测#ifdef是否存在唯一的系统变量来做到这一点
    例如

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    enum OPERATINGSYSTEM = {windows = 0, mac = 1, linux = 2 /*etc you get the point*/};

    void getOs(){
        #ifdef _WIN32
            return OPERATINGSYSTEM.windows
        #elif __APPLE__ //etc you get the point

        #endif
    }

    int main(){
        int id = getOs();
        if(id == OPERATINGSYSTEM.windows){
            system("CLS");
        }else if (id == OPERATINGSYSTEM.mac){
            system("CLEAR");
        } //etc you get the point

    }

    编辑:完全重做问题

    只需测试它们在哪个系统上,然后根据系统发送系统命令即可。尽管这将在编译时设置

    1
    2
    3
    4
    5
    #ifdef __WIN32
        system("cls");
    #else
        system("clear"); // most other systems use this
    #endif

    这是一种全新的方法!


    使用:clrscr();

    1
    2
    3
    4
    5
    6
    7
    8
    #include <iostream>
    using namespace std;
    int main()
          {          
             clrscr();
             cout <<"Hello World!" << endl;
             return 0;
          }


    最简单的方法是多次刷新流(理想情况下,刷新大于任何可能的控制台)1024 * 1024的大小可能是控制台窗口所没有的。

    1
    2
    3
    4
    5
    6
    7
    int main(int argc, char *argv)
    {
      for(int i = 0; i <1024*1024; i++)
          std::cout << ' ' << std::endl;

      return 0;
    }

    唯一的问题是软件游标。根据平台/控制台,闪烁的东西(或不闪烁的东西)将位于控制台的末尾,而不是其顶部。但是,这绝不希望引起任何麻烦。