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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With