【问题标题】:how to use switch case to take a string parameter?如何使用 switch case 获取字符串参数?
【发布时间】:2012-10-22 17:33:01
【问题描述】:

如何将字符串输入作为 switch case 参数?我可以用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;
}

【问题讨论】:

  • 我已经超过 12 年没有接触过 C++,但我敢肯定你不会。

标签: string switch-statement


【解决方案1】:

您不能在 C++ 中对字符串使用 switch 语句,抱歉。最好的办法是使用枚举。如果您不想使用枚举,那么您唯一的其他选择就是执行一堆 if else 来检查字符串是否相等。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我不能使用 if(sunType=="Type A") { //compute} ??
    • 我在 C++ 中开发的不多,但我没有看到 std::string 类的重载 == 运算符。
    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多