Search code examples
stringenumsc++98

How to assign string to enum using C++98?


I have declared an enum and a string

string SS;

enum CS {AA, BB, CC, DD};

and I want to create a variable named CN of type CS and assign the SS to enum CS.

I looked it up in the internet, most solutions are for C++11 and above. I tried to use map, but it would not work.

map<string, enum> CN;
  CN["AA"]=0;
  CN["BB"]=1;
  CN["CC"]=2;
  CN["DD"]=3;

Can anyone give me some suggestions? How do I create CS as a type enum CS? I will really appreciate it!


Solution

  • Your use of map is nearly right, so long as the values are initialised in function scope.

    I.e. this is OK

    std::map<std::string, CS> CN;
    
    int main() {
        CN["AA"]=AA;
        CN["BB"]=BB;
        CN["CC"]=CC;
        CN["DD"]=DD;
    
        // use CN
    }
    

    However this isn't

    std::map<std::string, CS> CN;
    CN["AA"]=AA; // can't have expressions at namespace scope
    CN["BB"]=BB;
    CN["CC"]=CC;
    CN["DD"]=DD;
    
    int main() {
        // try to use CN
    }