【问题标题】:User input to get enumeration value [duplicate]获取枚举值的用户输入[重复]
【发布时间】:2019-03-02 02:04:35
【问题描述】:

假设我有以下代码:

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

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

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

【问题讨论】:

  • 搜索“枚举到字符串”。周围有很多重复
  • 不是直接的,一旦编译,枚举值就是简单的整数变量。它与变量名相同。您无法从已编译的程序中访问变量名称和枚举名称,因为它们在已编译的程序中不再存在。

标签: c++


【解决方案1】:

如果您绝对必须这样做,这里有一个矫枉过正的解决方案:

#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

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 2015-04-26
    • 2012-12-28
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多