如何在 C++ 中清除控制台

Jinku Hu 2020年11月7日
如何在 C++ 中清除控制台

本文将介绍几种在 C++ 中清除控制台的方法。

使用 ANSI 转义码清除控制台

没有内置的 C++ 语言功能来操作控制台和清除输出文本。然而,ANSI 转义码可以是一种相对可移植的方式来实现这个目标。转义码是以 ASCII 转义字符和括号字符开头的字节序列,后面是参数。这些字符可以插入到输出字符串中,控制台将它们解释为命令而不是要显示的文本。

ANSI 代码包括多个控制台输出序列,具有上/下移动光标、行内擦除、滚动等功能和其他一些选项。下面的代码示例使用了显示中擦除序列,它可以清除整个屏幕,并且不删除回滚缓冲区。请注意,我们构建了一个单独的函数,命名为 clear,以使代码更加灵活和可读。

#include <iostream>

using std::cout;
using std::endl;

void Clear()
{
    cout << "\x1B[2J\x1B[H";
}

int main()
{
    cout << "Some console filling text ..." << endl;
    cout << "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n" << endl;
    Clear();

    return EXIT_SUCCESS;
}

另外,我们也可以插入同样的转义序列,并稍作修改(用 3 代替 2)来清除整个控制台屏幕,并删除回滚缓冲区,如下面的代码示例所示。一些有用的 ANSI 控制序列在下表中有描述。你也可以参考这个 Wikipedia 页面

代码 名称 效果
CSI n A 光标向上 将终端光标向上移动 n 个单元格。单元格的默认值是 1。如果光标已经在边缘,序列命令没有效果。
CSI n B 光标向下 将终端光标向下移动 n 个单元格,默认值为 1。如果光标已经在边缘,该序列命令没有任何效果。
CSI n J 清除显示 清除终端窗口的一部分。如果 n 为 0 或未指定,命令从光标的当前位置开始清除,直到窗口的末端。如果 n 为 1,命令从光标位置到窗口的起始位置进行清除。如果 n 是 2 个全屏,命令清除整个屏幕。如果 n 是 3,命令清除整个窗口,并删除回卷缓冲区中的行。
CSI n K 行内清除 删除该行的部分内容。如果 n 为 0 或未指定,命令从光标到行尾清除。如果 n 为 1,命令从光标到行首清除。如果 n 是 2,则清除整个行。
#include <iostream>

using std::cout;
using std::endl;

void ClearScrollback()
{
    cout << "\x1B[3J\x1B[H";
}

int main()
{
    cout << "Some console filling text ..." << endl;
    cout << "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n"
            "Another filler string for the stdout\n" << endl;
    ClearScrollback();

    return EXIT_SUCCESS;
}
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn