#include <iostream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#endif
// 函数模板,用于输出带有颜色的文本
template <typename T>
void printColored(const T& text, const std::string& colorCode) {
#ifdef _WIN32
// Windows 平台使用 SetConsoleTextAttribute
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
WORD colorAttribute = 0;
// 根据 ANSI 转义序列解析 colorCode 并设置 colorAttribute
if (colorCode == "\033[31m") {
colorAttribute = FOREGROUND_RED;
} else if (colorCode == "\033[32m") {
colorAttribute = FOREGROUND_GREEN;
} else if (colorCode == "\033[34m") {
colorAttribute = FOREGROUND_BLUE;
} else {
// 默认情况下不改变颜色
colorAttribute = 7; // 默认白色
}
SetConsoleTextAttribute(hConsole, colorAttribute);
std::cout << text << std::endl;
// 重置颜色
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#else
// UNIX-like 系统使用 ANSI 转义序列
std::cout << colorCode << text << "\033[0m" << std::endl;
#endif
}
int main() {
const std::string red = "\033[31m";
const std::string green = "\033[32m";
const std::string blue = "\033[34m";
// 输出彩色文本
printColored("这是红色文本", red);
printColored("这是绿色文本", green);
printColored("这是蓝色文本", blue);
return 0;
}