Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case on char*

It is a piece of code that gives me error:

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;
}

The switch(name) is where error happens. It says it must be a integral or enum type. So how do I do switch case, or equivalent, on a char* type?

like image 977
Ono Avatar asked Dec 17 '14 23:12

Ono


2 Answers

You cannot use switch here; as the error says, const char* is not supported. It's a good thing, too, because comparing two C-strings through pointers only compares the pointers, not the strings they point to (consider "hello" == "world").

Even if it were, you're trying to compare your C-string to multicharacter literals, which is certainly not what you intended, not least of all because they have type int and an implementation-defined value; I guess you meant to write "SRAD", not 'SRAD'.

Since you're using C++, you should do this:

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 {
   // ...
}

(I also fixed your use of name in the initialisation of D; Remy's right — you must have meant value here since "SRAD" cannot possibly be interpreted as a double.)

like image 111
Lightness Races in Orbit Avatar answered Oct 07 '22 23:10

Lightness Races in Orbit


Another option is to use a local map to store integral values corresponding to the string values, get the integral value from the string, then, use switch on the integral value.

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;
}
like image 39
R Sahu Avatar answered Oct 07 '22 23:10

R Sahu