如何使用switch case来获取字符串参数?

时间:2012-10-22 17:33:01

标签: string switch-statement

如何将字符串输入作为开关案例参数?我能够使用int而不是字符串。

如果我使用的是int输入,则以下代码可以正常工作,但如果我更改为字符串,则无效。

#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
class MissionPlan //start of MissionPlan class
{
    public:
    MissionPlan();
    float computeCivIndex(string,int,int,float,float);
}; //end of MissionPlan class

LocationData::LocationData()
{
    switch(sunType)
    {
        case "Type A": //compute 
                      break;
        case "Type B": //compute
                       break;
         //and many more case..
        default: break;
    }
}
int main()
{

    for(;;)
    {
    MissionPlan plan;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:3)

对不起,你不能在C ++中的字符串上使用switch语句。你最好打赌这是使用枚举。如果你不想使用枚举,那么你唯一的另一个选择是做一堆if检查字符串是否相等。

答案 1 :(得分:0)

C / C ++不支持带有字符串的switch语句。请改用if-else-if

if (sunType.compare("Type A") == 0) {
     //compute
} else if (sunType.compare("Type B") == 0) {
     // compute
} else {
     // default
}