2012-10-22 40 views
0

如何将字符串输入作为开关盒参数?我可以用int而不是字符串。如何使用switch case取一个字符串参数?

如果我使用的是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; 
} 
+0

我都没有超过12年感动C++,但我敢肯定你不能。 – jahroy

回答

3

不能在C++中的字符串中使用switch语句,抱歉。你最好在这里使用枚举。如果你不想使用枚举,那么你唯一的选择就是做一堆如果检查字符串是否相等的else。

0

C/C++不支持带字符串的switch语句。使用if-else-if代替:

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

我不能使用if(sunType ==“Type A”){//计算} ?? –

+0

我不用C++开发那么多,但是我没有看到'std :: string'类的重载'=='运算符。 –

+0

thx测试我的方式,它的工作原理:) –

相关问题