0

Say I have the following code:

int main()
{
    enum colors { red = 0, green = 1, blue = 2 };
    int myvar = instructions::red;
    cout << myvar;
}

This will (of course) output '0'.

However, is it in any way possible to obtain the color name via user input and store the corresponding number in 'myvar'?

2
  • search for "enum to string". There are lots of duplicates around Commented Sep 26, 2018 at 10:12
  • Not directly, once compiled the enum values are simply integer variables. It's the same as variable names. You cannot access to variable names and enum names from your compiled program because they simple don't exist anymore in the compiled program. Commented Sep 26, 2018 at 10:15

1 Answer 1

0

If you absolutely positively have to do this, here's an overkill solution:

#include <map>
#include <string>
#include <iostream>

typedef std::map<std::string, int> MyMapType;

MyMapType myMap = 
{
  {"RED", 0}, 
  {"GREEN", 1}, 
  {"BLUE", 2}
};

int getIntVal(std::string arg)
{
  MyMapType::const_iterator result = myMap.find(arg);
  if (result == myMap.end())
    return -1;
  return result->second;
}

int main()
{
  std::cout << getIntVal("RED") << std::endl;
  std::cout << getIntVal("GREEN") << std::endl;
  std::cout << getIntVal("BLUE") << std::endl;
  std::cout << getIntVal("DUMMY STRING") << std::endl;
}

gives the result:

0
1
2
-1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.