convert string to enum

Started by
13 comments, last by voyager838 18 years, 9 months ago
by the way
if you have to deal with flags and convert string to an enum
then one solution can be likely

also a pseudo code ;)


enum CAVE
{
MAP1 = 1 <
Advertisement
sorry about that error...

it seem to be standing

by the way
if you have to deal with flags too and convert string to an enum
then one solution can be likely

also a pseudo code ;)

enum CAVE
{
MAP1 = 1, // binary mask 0001
MAP2 = 2, // binary mask 0010
MAP3 = 4, // binary mask 0100
MAP4 = 8 // binary mask 1000
};


unsigned char convStr2Enum_flag (char *str)
{
unsigned char i = 0;
if (strstr(str,"MAP1")!=0)
i = MAP1;
if (strstr(str,"MAP2")!=0)
i |= MAP2;
if (strstr(str,"MAP3")!=0)
i |= MAP3;
if (strstr(str,"MAP4")!=0)
i |= MAP4;
return i;
}

and it dosent matter in what order you put this flag either.
example
MAP3|MAP2|MAP4 will give the result 14 and it respond to the mask 1110

/Voy
-= Code should be simple to understand =-
enum {  CAVE_ROCK,  CAVE_SPIKE,  CAVE_YOURMOTHER,  CAVE_EOF};const char * cave_strings[] ={  "Rock",  "Spike",  "YourMother",  "#"};int StringToEnum( const char * pstr ){  for (int i=CAVE_ROCK; i<CAVE_EOF; i++)  {    if (0==strcasecmp(pstr, cave_strings)) return i;  }  return CAVE_EOF;}

Fun stuff.
Actually, this may not work if your compiler can't do the cave_strings initializer, as this is a GCC extention of C, not ansi C. Plus that enum might be suspicious.
william bubel
Storing the flag as an integer would be nice and easy. Then you could just read an integer from the file and cast it to your enum, like so:

enum CAVE {    ROCK = 1,    STONE = 2};ifstream fin("info.txt",ios_base::in);int n;fin >>; n;CAVE cave = (CAVE)n;
"I just wanted to hang a picture on my wall, but somehow now I'm in the Amazon Jungle looking for raw materials." - Jekler
thanks all

it was really interesting problem.

The thing is maby very easy if you in the textfile are writing numbers
instead of the name in enum. but can it exist a simple solution
if i want to read a string from the textfile and then convert it
to the right number in enum?.

i havent found a simple solution for that yeat.

// greetings
voy
-= Code should be simple to understand =-

This topic is closed to new replies.

Advertisement