DaggerJay11
DaggerJay11

Reputation: 5

typedef enum input

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.

Upvotes: 0

Views: 522

Answers (2)

Anon Mail
Anon Mail

Reputation: 4770

What I use is an array of POD structs. The struct contains an enum and a const char * of the chars corresponding to the particular enum. Then I use std::find to look up either the enum or char * depending on which is needed.

The advantages of the array of PODs is that everything is initialized at program load time. No need to load a map.

The disadvantage is linear search of std::find. But it's never been an issue since I've never had a large number of enum values.

The above is all hidded in the implementation file. The header has just functions. Typically one to convert from enum to std::string and another to go from std::string to enum.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258678

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*.

Upvotes: 6

Related Questions