很简单。
有时候你想改变输出颜色,你会怎么办?
Windows的OIer朋友说了,用windowsAPI嘛!
但是,如果我是Linux系统呢??
很好,Linux发声了:你可以用\033转义符。
可是,有时候我们限于条件,需要使代码可以在多个平台上编译且需要输出带有颜色的字时,我们该怎么办??
简单!使用宏定义解决!
一般windows的编译程序会自动定义宏——_WIN32。
那么我们可以把代码写成这样:
#if defined(_WIN32)
#else
#endif
#if defined(_WIN32)||defined(_AMD64)||defined(_ARM64)
#define SYSTEM 1
#include<windows.h>//WinAPI包含Sleep
#define cls system("cls")
#define c_normal system("color")
#define f_cyan color("09")
#define f_purple color("05")
#define f_blue color("01")
#define f_yellow color("06")
#define f_green color("02")
#define f_red color("04")
#define f_grey color("08")
void color(string cl){
for(int i=0;i<cl.size();i++){
if(cl[i]>='a'&&cl[i]<='z'){
cl[i]=cl[i]-32;
}
}
if(cl=="HELP"){
system("color /?");
}else if(cl=="NORMAL"){
c_normal;
}
int a,b;
if(cl[0]>='0'&&cl[0]<='9'){
a=cl[0]-'0';
}else{
a=cl[0]-55;
}
if(cl[1]>='0'&&cl[1]<='9'){
b=cl[1]-'0';
}else{
b=cl[1]-55;
}
if(cl=="normal"){
a=0;b=0;
}
HANDLE handle;
handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle,a*16+b);
}
string colorset;
#else
#define SYSTEM 0
#define clear cout<<"\033c"
void Sleep(int a){
usleep(a*1000);
}
#define c_normal cout<<"\033[000m"
#define f_cyan cout<<"\033[36;1m"
#define f_purple cout<<"\033[35;1m"
#define f_blue cout<<"\033[34;1m"
#define f_yellow cout<<"\033[33;1m"
#define f_green cout<<"\033[32;1m"
#define f_red cout<<"\033[31;1m"
#define f_grey cout<<"\033[30;1m"
string colorset="normal";
void cls();
extern void color(string s){
if(s=="help"){
cout<<"Linux: 输入"<<endl;
cout<<"normal 默认"<<endl;
cout<<"hide \033[31;1m停用\033[000m"<<endl;
cout<<"show \033[31;1m停用\033[000m"<<endl;
cout<<"0 灰"<<endl;
cout<<"1 红"<<endl;
cout<<"2 绿"<<endl;
cout<<"3 黄"<<endl;
cout<<"4 蓝"<<endl;
cout<<"5 紫"<<endl;
cout<<"6 青"<<endl;
return;
}
if(s=="normal"){
c_normal;
colorset=s;
return;
}else if(s=="hide"||s=="show"){
cout<<"\033[31;1m命令已停用\033[000m"<<endl;
return;
}
switch(s[0]){
case '0':
colorset=s;
f_grey;
break;
case '1':
colorset=s;
f_red;
break;
case '2':
colorset=s;
f_green;
break;
case '3':
colorset=s;
f_yellow;
break;
case '4':
colorset=s;
f_blue;
break;
case '5':
colorset=s;
f_purple;
break;
case '6':
colorset=s;
f_cyan;
break;
default:
cout<<"Error!"<<endl;
}
}
void cls(){
clear;
if(colorset=="normal"){
}else{
color(colorset);
}
}
#define cls cls()
#endif
讨论区
页面版本: 3, 最后编辑于: 07 Jan 2023 02:23
这是好的。
悟已往之不谏,知来者之可追。
赏
当知识之圆不断扩大,未知的边界亦会同样增加。
As our circle of knowledge expands,so does the circumference of darkness surrounding it.
事Linux罢
当知识之圆不断扩大,未知的边界亦会同样增加。
As our circle of knowledge expands,so does the circumference of darkness surrounding it.
草,手滑打错了
是Windows API罢
悟已往之不谏,知来者之可追。
草!破键盘!
毕竟我用远程桌面在手机上访问电脑来着