问题描述
我正在尝试更改c ++中文本的颜色,我能找到的唯一答案是C语言而不是C ++语言。我尝试使用conio.h,但不知道如何使用它。有人可以帮忙吗?
解决方法
在C ++方面,文本着色并不是真的。在某些Unix终端中,您可以直接在程序中直接使用\e[0;31m message \e[0m
之类的代码(尽管您可能希望创建一个API以便于使用)。但是,这在Windows控制台中不起作用。这取决于所使用的操作系统和终端。
如果您不需要坚持使用非跨平台库conio.h
。我建议使用跨平台解决方案:仅标头,moderc C ++ rang
库。我在大多数项目中都使用过它,真的很容易使用
我发现了如何使用windows.h更改文本的颜色。这是我使用的代码示例(从https://cboard.cprogramming.com/复制)。
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); // h is your link to the console
SetConsoleTextAttribute(h,1); cout << "Sentence in blue" << '\n'; // 1 happens to be blue
SetConsoleTextAttribute(h,2); cout << "Sentence in green" << '\n'; // 2 is green
SetConsoleTextAttribute(h,4); cout << "Sentence in red" << '\n'; // 4 is red
SetConsoleTextAttribute(h,7); cout << "Sentence in white" << '\n'; // etc.
}