Jos*_*ake 29 c++ switch-statement
我可能在寻找一些东西,但在C++中是否有一种简单的方法可以将案例分组在一起而不是单独写出来?我记得基本上我可以做到:
SELECT CASE Answer
CASE 1, 2, 3, 4
Run Code Online (Sandbox Code Playgroud)
C++中的示例(对于那些需要它的人):
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1:
case 2:
case 3:
case 4:
cout << "You need more cars. ";
break;
case 5:
case 6:
case 7:
case 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Leo*_*son 29
AFAIK所能做的就是省略返回以使C++中的东西更紧凑:
switch(Answer)
{
case 1: case 2: case 3: case 4:
cout << "You need more cars.";
break;
...
}
Run Code Online (Sandbox Code Playgroud)
(当然,您也可以删除其他退货.)
小智 17
你当然可以.
您可以使用大小写x ... y作为范围
例:
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1 ... 4:
cout << "You need more cars. ";
break;
case 5 ... 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
确保在编译器中启用了"-std = c ++ 0x"标志
mar*_*cog 12
不,但你可以使用if
- else if
- else
链来实现相同的结果:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
Run Code Online (Sandbox Code Playgroud)
您可能还想处理0辆汽车的情况,然后也可能通过抛出异常来处理负数车辆的意外情况.
PS:我已经重命名Answer
为answer
因为用大写字母启动变量被认为是不好的风格.
作为旁注,像Python这样的脚本语言允许良好的if answer in [1, 2, 3, 4]
语法,这是实现您想要的灵活方式.
您的示例与构造一样简洁switch
。
您无法删除关键字case
.但是你的例子可以像这样写得更短:
switch ((Answer - 1) / 4)
{
case 0:
cout << "You need more cars.";
break;
case 1:
cout << "Now you need a house.";
break;
default:
cout << "What are you? A peace-loving hippie freak?";
}
Run Code Online (Sandbox Code Playgroud)