Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from String to Enum in C

Tags:

c

string

enums

Is there a convienent way to take a string (input by user) and convert it to an Enumeration value? In this case, the string would be the name of the enumeration value, like so:

enum Day
{
    Sunday = 0,
    Monday = 1,
    ...
}

So that if the user gave the name of a Day, it would be able to parse that to the corresponding Enum value.

The trick is, I have over 500 values I'm working with, and they are spread out across multiple enumerations.

I know of the Enum.Parse Method in c#, so is there some form of this in c?

like image 930
Nealon Avatar asked May 30 '13 19:05

Nealon


1 Answers

The standard way to implement it is something along the lines of:

typedef enum {value1, value2, value3, (...) } VALUE;

const static struct {
    VALUE      val;
    const char *str;
} conversion [] = {
    {value1, "value1"},
    {value2, "value2"},
    {value3, "value3"},
       (...)
};

VALUE
str2enum (const char *str)
{
     int j;
     for (j = 0;  j < sizeof (conversion) / sizeof (conversion[0]);  ++j)
         if (!strcmp (str, conversion[j].str))
             return conversion[j].val;    
     error_message ("no such string");
}

The converse should be apparent.

like image 128
wallyk Avatar answered Sep 23 '22 03:09

wallyk