在char*上切换案例

Ono*_*Ono 3 c++ string char switch-statement

这是一段代码,它给了我错误:

const char* name = pAttr->Name(); // attribute name
const char* value = pAttr->Value(); // attribute value

switch(name) // here is where error happens: must have integral or enum type
{
case 'SRAD':    // distance from focal point to iso center
    double D = atof(value);
    break;
case 'DRAD':    // distance from iso center to detector
    break;
default:
    break;
}
Run Code Online (Sandbox Code Playgroud)

switch(name)是发生错误的地方.它说它是一个整体或枚举类型.那么我该怎么做一个char*类型的switch case或者等价?

Lig*_*ica 11

你不能switch在这里使用; 如错误所示,const char*不受支持.这也是一件好事,因为通过指针比较两个C字符串只比较指针,而不是它们指向的字符串(考虑"hello" == "world").

即使它是,你试图将你的C字符串与多字符文字进行比较,这当然不是你想要的,尤其是因为它们有类型int和实现定义的值; 我想你的意思是写"SRAD",而不是'SRAD'.

由于您使用的是C++,因此您应该这样做:

const std::string name = pAttr->Name();
const std::string value = pAttr->Value();

if (name == "SRAD") {
   double D = atof(value.c_str());  // use std::stod(value) in C++11
   // ...
}
else if (name == "DRAD") {
   // ...
}
else {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

(我还修正了你name在初始化时的使用D;雷米的权利 - 你必须在value这里意味着,因为"SRAD"不可能被解释为double.)


R S*_*ahu 5

另一种选择是使用本地map存储与字符串值对应的整数值,从字符串中获取整数值,然后使用switch该整数值。

enum { SRAD = 1, DRAD, ... };

static std::map<std::string, int> localMap;
// Fill up the map.
if ( localMap.empty() )
{
   localMap["SRAD"] = SRAD;
   localMap["DRAD"] = DRAD;
}

const char* name = pAttr->Name(); // attribute name
const char* value = pAttr->Value(); // attribute value

int val = localMap[name];

switch (val)
{
    case SRAD:    // distance from focal point to iso center
    {
        double D = atof(value);
        break;
    }

    case DRAD:    // distance from iso center to detector
        break;

    default:      // name is unknown
        break;
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来是正确的,但您要付出地图索引复杂性的代价。为什么不使用 if-else 条件语句? (3认同)
  • 这很好,只是如果未找到“name”,并且您已将 0 定义为“SRAD”,则“localMap[name]”将返回 0。最好将枚举值从 1 开始,这样您就可以处理未知名称的 0。另外,“atof(name)”应该是“atof(value)”,这是OP代码中的拼写错误。`atof("SRAD")` 总是会失败。 (2认同)