如何使用 ANSI 转义码在控制台上输出彩色文本 [英] How to use the ANSI Escape code for outputting colored text on Console

查看:56
本文介绍了如何使用 ANSI 转义码在控制台上输出彩色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处阅读了有关 ANSI-C 转义码的信息.尝试在 C/C++ printf/cout 中使用它对输出到 consolde 的文本进行着色,但没有成功.

I read about ANSI-C escape codes here. Tried to use it in C/C++ printf/cout to colorize the text outputted to consolde but without sucess.

代码:

#include <iostream>

 #include <cstdio>

int main()
{

    int a=3, b=5;
    int &ref = a;

    ref = b;

    //cout << "15532m" << a << b <<'
'; //here it prints m→m 5, no colored text
    printf("15532m %d",a); //here to it prints same - m→m 5, 

    getchar();

}

如何使用这些转义码将彩色文本输出到控制台?

How to use these escape codes to output colored text to console?

我错过了什么吗?

在一些 C++ 代码中,我看到了对这个函数的调用

In some C++ code I saw a call to this function

textcolor(10);

但是它在 g++ 和 Visual Studio 中给出了编译错误.哪个编译器有这个功能?有什么细节吗?

But it gives compilation errors in g++ and in Visual Studio. Which compiler had this function available? Any details?

推荐答案

恐怕你忘记了 ESC 字符:

I'm afraid you forgot the ESC character:

#include <cstdio>

int main()
{
    printf("%c[%dmHELLO!
", 0x1B, 32);
}

不幸的是,它只适用于支持 ANSI 转义序列的控制台(如使用 bash 的 linux 控制台,或使用 ansi.sys 的旧 Windows 控制台)

Unfortunately it will only work on consoles that support ANSI escape sequences (like a linux console using bash, or old Windows consoles that used ansi.sys)

这篇关于如何使用 ANSI 转义码在控制台上输出彩色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆