简体   繁体   English

ANSI 转义码无法正常工作 [C++]

[英]ANSI escape code not working properly [C++]

I am using the ANSI escape code to print colored output.我正在使用 ANSI 转义码来打印彩色输出。

I am getting proper colored output in vs code integrated terminal.我在 vs 代码集成终端中获得了正确的彩色输出。 在此处输入图像描述

But when I am running the program in external command-prompt/Powershell, I am not getting the expected colored output.但是当我在外部命令提示符/Powershell 中运行程序时,我没有得到预期的彩色输出。

在此处输入图像描述

My program looks something like this:我的程序看起来像这样:


#define RESET   "\033[0m"
#define RED  "\x1B[31m"
#define GREEN  "\x1B[32m"

int main(int argc, char** argv){
    if(argc != 1){
        std::cout << RED ">> Invalid Arguments!" RESET;
    }else{
        if(verify_password()){
            ...
            ...
            ...
        }else{
            std::cout <<  "\n>> " RED "Invalid Password!" RESET;
        }
    }
    return 0;
}

Complete Code 完整代码

NOTE : One weird thing I observed is that if I am entering the correct password then everything is working fine in both terminals(getting proper colors).注意:我观察到的一件奇怪的事情是,如果我输入了正确的密码,那么两个终端中的一切都正常(获得正确的颜色)。 But the problem is when either I am entering an incorrect password or an invalid amount of arguments但问题是当我输入错误的密码或无效数量的参数时

What might be the reason for this?这可能是什么原因?

EDIT: I figured out a way to make it work.编辑:我想出了一种让它工作的方法。 I find out that in order to make these escape codes work I need to have at least one call to system() function.我发现为了使这些转义码起作用,我需要至少调用一次system()函数。 But still, I am not sure how these things are connected.但是,我仍然不确定这些东西是如何联系起来的。

Historically, consoles on Windows required use of the console API in the Windows SDK in order to do effects like color.从历史上看,Windows 上的控制台需要使用 Windows SDK 中的控制台 API才能执行颜色等效果。 But recent versions of Windows now support escape codes (and even UTF-8), but programs have to opt-in by callingSetConsoleMode with ENABLE_VIRTUAL_TERMINAL_PROCESSING .但是最近的 Windows 版本现在支持转义码(甚至 UTF-8),但程序必须通过调用SetConsoleMode 和 ENABLE_VIRTUAL_TERMINAL_PROCESSING来选择加入。 (Opting in preserves backward compatibility for older programs that aren't using escape codes or UTF-8.) (选择加入可以为不使用转义码或 UTF-8 的旧程序保留向后兼容性。)

If you're getting color in some places and not others, then I'd guess there's a problem related to the state the terminal/console is in when sending the escape codes.如果您在某些地方而不是其他地方获得颜色,那么我猜想存在与发送转义码时终端/控制台所处状态有关的问题。 For example, if the terminal thinks it's already processing an escape code and a new one begins, it might not recognize either.例如,如果终端认为它已经在处理一个转义码并且开始一个新的转义码,它也可能无法识别。 I suppose this might also be a problem if one part of the program uses escape codes but another part uses the Console API.我想如果程序的一部分使用转义码但另一部分使用控制台 API,这也可能是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM