如何将用户输入(字符串)映射到Enum值

How to map User input (string) to Enum Value?

本文关键字:映射 Enum 字符串 用户 输入      更新时间:2023-10-16

我正在将单词转换为数字。我有一个数字的Enum。是否有任何方法映射用户输入例如:"3"转换为3检查枚举数据3。我不想对每个数字都使用if()或switch()。

请帮。

使用map

的例子:

enum Choice {Unknown, One, Two, Three};
Choice getChoice(std::string const& s)
{
   static std::map<std::string, Choice> theMap = {{"One", One}, {"Two", Two}, {"Three", Three}};
   return theMap[s];
}

只返回一个int,您可以使用:

int getInt(std::string const& s)
{
   static std::map<std::string, int> theMap = {{"One", 1, {"Two", 2}, {"Three", 3}};
   if ( theMap.find(s) == theMap.end() )
   {
      // Deal with exception.
   }
   return theMap[s];
}

考虑以下使用map而不使用enum:

#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    // map for convercion
    map<string, int> equivalents;
    equivalents["zero"] = 0;
    equivalents["one"] = 1;
    equivalents["two"] = 2;
    equivalents["three"] = 3;
    equivalents["four"] = 4;
    equivalents["five"] = 5;
    equivalents["six"] = 6;
    equivalents["seven"] = 7;
    equivalents["eight"] = 8;
    equivalents["nine"] = 9;
    // conversion example
    string str;
    cin >> str;
    // make string lowercase
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    // check correctness of input and conversion
    if( equivalents.count(str) )
    {
        cout << equivalents[str] << endl;
    }
    else
    {
        cout << "Incorrect input" << endl;
    }
    return 0;
}