103

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

4

19 回答 19

75

对于纯 C++

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

该程序可能正在打印到打印机,直接输出到文件,或者被重定向到另一个程序的输入以供其关心。即使您可以在 C++ 中清除控制台,也会使这些情况变得更加混乱。

请参阅 comp.lang.c++ FAQ 中的此条目:

特定于操作系统

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

对于 Windows(如您的标签中所示),请查看此链接:

编辑:这个答案之前提到 using system("cls");,因为微软说要这样做。然而,评论中已经指出,这不是一件安全的事情。由于这个问题,我删除了指向 Microsoft 文章的链接。

库(有点便携)

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

于 2011-06-26T19:47:46.533 回答
56

对于 Windows,通过控制台 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);
}

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

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

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

使用system它只是丑陋的。

于 2011-06-26T23:51:03.950 回答
30

对于 Linux/Unix 和其他一些,但不是 10 TH2 之前的 Windows:

printf("\033c");

将重置终端。

于 2017-05-10T06:05:20.713 回答
30

对我来说最简单的方法,无需重新发明轮子。

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
}
  • Windows上,您可以使用“conio.h”头文件并调用clrscr函数来避免使用系统函数。
#include <conio.h>
clrscr();
  • Linux 上,您可以使用 ANSI Escape 序列来避免使用系统函数。检查此参考ANSI Escape Sequences
    std::cout<< u8"\033[2J\033[1;1H"; 
  • MacOS上 调查...
于 2018-10-19T15:39:17.893 回答
8

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

#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 或终端函数

#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" ) );
  }
于 2016-09-29T06:31:41.380 回答
5

要清除屏幕,您首先需要包含以下标题:

#include <stdlib.h>

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

system("CLS");

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

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

using namespace std;

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

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

于 2014-05-29T07:35:09.197 回答
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;
}
于 2015-05-09T07:37:39.377 回答
3

在 Windows 中:

#include <cstdlib>

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

在 Linux/Unix 中:

#include <cstdlib>

int main() { 
    std::system("clear");
    return 0;
}
于 2015-07-05T15:57:37.470 回答
3

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

void clearScreen(){
    int clear = 5;
    do {
        cout << endl;
        clear -= 1;
    } while (clear !=0);
}
于 2017-05-06T05:10:55.530 回答
2

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

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

  2. 系统(“cls”)(头文件:stdlib.h)

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

于 2019-08-21T12:35:02.777 回答
2

用于system("cls")清屏:

#include <stdlib.h>

int main(void)
{
    system("cls");
    return 0;
}
于 2016-06-12T07:38:50.020 回答
1

如果您使用的是 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);
}

这就是 system("cls"); 无需创建流程即可。

于 2021-01-24T03:24:24.767 回答
1

效果很好:

#include <windows.h>

void clearscreen()
{
    HANDLE hOut;
    COORD Position;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    Position.X = 0;
    Position.Y = 0;
    SetConsoleCursorPosition(hOut, Position);
}
于 2021-11-26T23:41:55.880 回答
0

这是一个简单的方法:

#include <iostream>

using namespace std;

int main()
{
    cout.flush(); // Flush the output stream
    system("clear"); // Clear the console with the "system" function
}
于 2018-05-14T13:20:08.820 回答
-1

使用 System::Console::Clear();

这将清除(清空)缓冲区

于 2014-11-26T04:05:26.323 回答
-1
#include <cstdlib>

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

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

}

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

于 2017-04-02T09:47:28.260 回答
-1
#include <bits/stdc++.h>
int main()
{
    int arr[] = {10, 5, 8 ,20, 2, 18};
    int n = sizeof(arr)/sizeof(arr[0]);
    system("cls"); 
 

    print_array(arr, n);
    return 0;
}

这很简单。system("cls"); 在开始打印任何东西之前先放行。

于 2021-06-17T19:57:56.210 回答
-4

使用:clrscr();

#include <iostream>
using namespace std;
int main()
      {           
         clrscr();
         cout << "Hello World!" << endl;
         return 0;
      }
于 2015-04-25T20:13:52.520 回答
-7

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

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

  return 0;
}

唯一的问题是软件光标;取决于平台/控制台的闪烁的东西(或不闪烁的东西)将位于控制台的末端,而不是它的顶部。但是,希望这永远不会引起任何麻烦。

于 2011-06-27T03:52:38.067 回答