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
There isn't a direct way, but with C, you improvise. Here's an old trick. Purists may balk at this. But it's a way to manage this kind of stuff somewhat sanely. Uses some preprocessor tricks.
In constants.h put in the following:
CONSTANT(Sunday, 0)
CONSTANT(Monday, 1)
CONSTANT(Tuesday, 2)
In main.c:
#include
#define CONSTANT(name, value) \
name = value,
typedef enum {
#include "constants.h"
} Constants;
#undef CONSTANT
#define CONSTANT(name, value) \
#name,
char* constants[] = {
#include "constants.h"
};
Constants str2enum(char* name) {
int ii;
for (ii = 0; ii < sizeof(constants) / sizeof(constants[0]); ++ii) {
if (!strcmp(name, constants[ii])) {
return (Constants)ii;
}
}
return (Constants)-1;
}
int main() {
printf("%s = %d\n", "Monday", str2enum("Monday"));
printf("%s = %d\n", "Tuesday", str2enum("Tuesday"));
return 0;
}
You can try other variations of the basic idea.