C++如何从控制台中删除一行?

问题描述 投票:0回答:1

我有这样一段代码,我在工作中使用了一个switch语句,我想做的是当任何一个无效的选项被选中时,程序应该显示一条消息,然后在一段时间后,只清除消息,而保持选项在屏幕上。我想做的是,当任何无效的选项被选中时,程序应该显示一条消息,然后在一段时间后只清除消息,而保持选项仍在屏幕上。在我目前的代码中,我使用Windows.h库的Sleep函数进行暂停,也使用goto回到询问选项,但似乎无法弄清楚如何从屏幕上清除错误消息。我无法使用 system("cls"); 因为我在这个选项选择之前有一个菜单,有点像登录,所以我不希望它消失,直到一个有效的选项被选择。

cout<<endl<<"\t\t\t\t\t\t                            - Access Denied! -"<<endl;
cout<<"\t\t\t\t\t\t                         + Press [1] To Try Again. +"<<endl;
cout<<"\t\t\t\t\t\t                         + Press [2] To Go Back. +"<<endl;
char TryAgain = ' ';
cout<<"\t\t\t\t\t\t                                 >>[ ]<< ";
InvalidOption:
SetConsoleCursorPosition(hStdout, { 84, 14 });
cin>>TryAgain;
switch (TryAgain)
{
    case '1':
        goto LoginAgain;
    case '2':
        break;
    default:
        {
            cout<<"\t\t\t\t\t                            Select A Valid Option!";
            Sleep ( 450 );
            cout << "\b";
            goto InvalidOption;
        }
}

是的,我使用了大量的 /t 也许还有很多其他的东西,但它只是我在尝试的一个示例代码,而不是直接在我的原始项目上进行实验。

c++
1个回答
1
投票

如果你的终端支持,你可以使用ANSI转义码(此处, 此处),提供了更高级的控制台文本控制功能,可以删除多行、打印彩色文本、全部跳过。

一般格式为 ESC[X 哪儿 ESC 是ASCII转义字符(0x1b),以及 X 是命令。很多时候 X 前面会有一个整数参数,比如在 ESC[1A 下面 1 是向上移动的行数。

例子。

#include <iostream>

// Erases `count` lines, including the current line
void eraseLines(int count) {
    if (count > 0) {
        std::cout << "\x1b[2K"; // Delete current line
        // i=1 because we included the first line
        for (int i = 1; i < count; i++) {
            std::cout
            << "\x1b[1A" // Move cursor up one
            << "\x1b[2K"; // Delete the entire line
        }
        std::cout << "\r"; // Resume the cursor at beginning of line
    }
}

int main() {
    std::cout << "\t\t\t\t\t\t         text" << std::endl;
    std::cout << "\t\t\t\t\t\t         more text" << std::endl;
    std::cout << "\t\t\t\t\t\t      even   more text \t\t" << std::endl;
    eraseLines(4);
    std::cout << "No one's here..." << std::endl;
}

工作在 重置 和Cygwin Mintty


0
投票

你也许可以使用回车字符 \r. 它通常与行式进料一起使用。\n但它的独立功能是 "将打印位置返回到行首"。在一些终端上,如果你打印了,就会打印出一堆空格,覆盖你的信息。

cout << "\t\t\t\t\t Your stuff" << flush; // flush may be needed when you don't output \n
Sleep(450);
cout << "\r                          \r"; // return to start of line, print spaces, return again

所有这些的前提是你不在任何地方输出换行。如果你这样做,所有的东西都会丢失,你必须清除整个屏幕。

© www.soinside.com 2019 - 2024. All rights reserved.