How to use the ANSI Escape code for outputting colored text on Console(如何使用 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 转义码在控制台上输出彩色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 ANSI 转义码在控制台上输出彩色文本


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16