typedef枚举输入 [英] typedef enum input

查看:176
本文介绍了typedef枚举输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

origin_t国家;
char * current;
cin>> current;

如何设置 Country c-String 当前由用户输入?
除了比较一个接一个,因为我们有一个大的列表?
最快的方式? $ C ++中的<$ c>和 string char *



一个有效的方法是有一张地图:

  #include< map& 
#include< string>

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

std :: map< std :: string,origin_t>国家;
个国家/地区[未知] =未知;
countries [USA] =美国;
// ...

origin_t国家;
std :: string current;
cin>> current;
国家= countries [当前];

请注意,在我的示例中,我使用 std :: string 而不是 char * ,这是你应该做的,除非你有强烈的理由使用 char *


if we have this in c++:

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

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

how can we set Country to be the c-String current inputed by the user? other than comparing one by one since we have a large list? fastest way? thank you very much.

解决方案

There's no direct conversion between enum and string or char* in C++ as there is in Java.

An efficient way is to have a map:

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

Note that in my sample I'm using std::string instead of char*, which is what you should do unless you have strong reasons to use char*.

这篇关于typedef枚举输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆