如何将用户输入(字符串)映射到Enum值
How to map User input (string) to Enum Value?
我正在将单词转换为数字。我有一个数字的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;
}
相关文章:
- enum是C++中的宏变量还是整数变量
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 是否可以从int转换为enum类类型
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在映射c++中,使用enum作为键来设置和获取值
- 如何将用户输入(字符串)映射到Enum值
- 是否可以将int(enum)映射为类型
- 需要从enum(类)到std::binary_function的映射