如需使用16色版请参照:C++控制台输出彩色字体&背景(16色版)
1、 效果演示
下面将演示如何打印256种颜色的字体和背景,以及展示最终效果
#include <iostream>
using namespace std;
void print_256_colours_txt()
{
for (int i = 0; i < 256; i++)
{
if (i % 16 == 0 && i != 0)
cout << endl;
printf("\033[38;5;%dm %3d\033[m", i, i);
}
}
void print_256_colours_background()
{
for (int i = 0; i < 256; i++)
{
if (i % 16 == 0 && i != 0)
cout << endl;
printf("\033[48;5;%dm %3d\033[m", i, i);
}
}
int main()
{
//打印256种颜色字体
print_256_colours_txt();
cout << endl;
//打印256种颜色背景
print_256_colours_background();
return 0;
}
控制台打印结果如图:
2、代码封装
为了更简易地使用以上代码并且提高适用范围,对以上的代码进行以C++语言为基础的封装,封装后的函数如下所示
#include <iostream>
using namespace std;
//彩色输出函数(256色)
template<typename T> //T表示任何可以被cout输出的类型
void ColorCout_256(T t, const int ForeColor = 7, const int BackColor = 0)
{
//ForeColor和BackColor的取值区间为[0,255]
cout << "\033[" << "38;5;" << ForeColor << "m";
cout << "\033[" << "48;5;" << BackColor << "m";
cout << t << "\033[m";
}
int main()
{
ColorCout_256("hello world", 208, 32);
return 0;
}
运行结果:
3、注意事项
使用以上函数无需引入任何库,适用Linux发行版(如Ubuntu或macOS)和Windows 10版本1511后的版本,使用时注意自身系统是否支持以上功能,如不支持请使用16色版本。