#include
int main() {
int number = 2;
switch (number) {
case 1:
std::cout << "Number is 1" << std::endl;
break;
case 2:
case 3:
std::cout << "Number is 2 or 3" << std::endl;
break;
default:
std::cout << "Number is not 1, 2, or 3" << std::endl;
}
return 0;
}
当上面的代码被编译并执行时,会产生以下结果:
Number is 2 or 3
1 篇笔记
C++ Linux 下字符串简单显示颜色的示例,使用switch语句:
#include
#include
using namespace std;
void printcolor(string color, string str)
{
int clr;
string head;
string tail;
string display;
if(color=="red") clr=1;
if(color=="green") clr=2;
switch(clr){
case 1:{
head="\033[31m";
tail="\033[0m";
display=head+str+tail;
break;
}
case 2:{
head="\033[32m";
tail="\033[0m";
display=head+str+tail;
break;
}
default:{
display=str;
break;
}
}
cout << display << endl;
}
int main ()
{
printcolor("red", "helloworld!");
printcolor("green", "helloworld!");
return 0;
}