用户输入以获得枚举值

时间:2018-09-26 10:11:31

标签: c++

说我有以下代码:

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

(当然)这将输出“ 0”。

但是,是否可以通过用户输入获取颜色名称并将相应的数字存储在'myvar'中?

1 个答案:

答案 0 :(得分:0)

如果您绝对肯定要这样做,这是一个过分解决的方法:

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

给出结果:

0
1
2
-1