typedef枚举输入

时间:2012-04-13 12:55:03

标签: c++ enums typedef

如果我们在c ++中有这个:

typedef enum {Unknown,USA,Canada,France,England,Italy,Spain,Australia,} origin_t;

origin_t Country;
char *current;
cin>>current;

我们如何将Country设置为用户输入的c-String current? 因为我们有一个大的列表,一个接一个地比较? 最快的方式? 非常感谢你。

2 个答案:

答案 0 :(得分:6)

C ++中的enumstringchar*之间没有直接转换,就像在Java中一样。

有效的方法是制作地图:

#include <map>
#include <string>

typedef enum {Unknown,USA,Canada,France,England,Italy,Spain,Australia,} origin_t;

std::map<std::string, origin_t> countries;
countries["Unknown"] = Unknown;
countries["USA"] = USA;
//...

origin_t Country;
std::string current;
cin>>current;
Country = countries[current];

请注意,在我的示例中,我使用的是std::string而不是char*,除非您有充分理由使用char*,否则应该执行此操作。

答案 1 :(得分:0)

我使用的是一系列POD结构。该结构包含一个枚举和一个与特定枚举对应的字符的const char *。然后我使用std :: find来查找enum或char *,具体取决于所需的。

POD阵列的优点是一切都在程序加载时初始化。无需加载地图。

缺点是std :: find的线性搜索。但它从来都不是一个问题,因为我从未有过大量的枚举值。

以上内容全部隐藏在实现文件中。标题只有功能。通常一个是从枚举转换为std :: string,另一个是从std :: string转换为enum。