如何更改 Windows 控制台应用程序中的文本或背景颜色

2023-07-01C/C++开发问题
32

本文介绍了如何更改 Windows 控制台应用程序中的文本或背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

哪个 C++ 函数会更改文本或背景颜色(MS Visual Studio)?比如cout<<"This text";如何让"This text"变成红色.

Which C++ function changes text or background color (MS Visual studio)? For example cout<<"This text"; how to make "This text" red color.

推荐答案

颜色不是 C++ 的东西,而是 终端 的属性.如果您的终端使用 ANSI(例如,任何 Linux 终端,或 DOS 或 Windows NT,如果您将 DEVICE=C:DOSansi.sys 添加到您的 config.sys,或以后的Windows如果你用cmd.exe/kansicon调用shell,那么你可以试试下面的噱头:

Colour isn't a C++ thing, but a property of your terminal. If your terminal speaks ANSI (e.g. any Linux terminal, or DOS or Windows NT if you add DEVICE=C:DOSansi.sys to your config.sys, or later Windows if you call the shell with cmd.exe /kansicon), then you can try the following gimmick:

#define ANSI_COLOR_RED     "x1b[31m"
#define ANSI_COLOR_GREEN   "x1b[32m"
#define ANSI_COLOR_YELLOW  "x1b[33m"
#define ANSI_COLOR_BLUE    "x1b[34m"
#define ANSI_COLOR_MAGENTA "x1b[35m"
#define ANSI_COLOR_CYAN    "x1b[36m"

#define ANSI_COLOR_BRIGHT  "x1b[1m"
#define ANSI_COLOR_RESET   "x1b[0m"


std::cout << ANSI_COLOR_RED "Hello World
" ANSI_COLOR_RESET;

维基百科有一个ANSI 转义序列列表.

这篇关于如何更改 Windows 控制台应用程序中的文本或背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6