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'?

Thijmen
  • 374
  • 2
  • 14
  • search for "enum to string". There are lots of duplicates around – 463035818_is_not_an_ai Sep 26 '18 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. – Jabberwocky Sep 26 '18 at 10:15

1 Answers1

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
corsel
  • 315
  • 2
  • 12