randy1200 said:
The following enum is given to me, and I can't change it:
enum yo { ONE, TWO, THREE };
I have the following:
char test[10] = "ONE";
Any ideas on how to see if the string in "test" is in the enum, and return
the enum number if true?
You can think "generative programming", or how to automate some
programming tasks.
I wrote you a little scrit in CodeWorker (
http://www.codeworker.org).
It parses a C file, looking for every enum declaration inside. Then,
it writes a string-to-enum function for each of them.
Advantage: if someone adds or renames or removes some enum identifiers
in a enum type, you just have to run the script, which could be a part
of your build process.
The script also handles enum declarations like :
enum pets { GOAT, DOG = 3, CAT = 0x05, MOUSE };
And it generates the following code:
int str2yo_enum(const char* name, enum yo* val) {
int err = 0;
if (strcmp(name, "ONE") == 0) *val = ONE;
else if (strcmp(name, "TWO") == 0) *val = TWO;
else if (strcmp(name, "THREE") == 0) *val = THREE;
else err = -1;
return err;
}
int str2pets_enum(const char* name, enum pets* val) {
int err = 0;
if (strcmp(name, "GOAT") == 0) *val = GOAT;
else if (strcmp(name, "DOG") == 0) *val = DOG;
else if (strcmp(name, "CAT") == 0) *val = CAT;
else if (strcmp(name, "MOUSE") == 0) *val = MOUSE;
else err = -1;
return err;
}
The script is (save it to "str2enum.cwp"):
str2enum ::=
// ignore whitespaces and C comments
// between each BNF terminal or non-terminal
#ignore(C++)
// look for every enum declaration
[
// jump to the next enum declaration
->[
#readIdentifier:sId
#nextStep
#check(sId == "enum")
// interesting only if it's a named enum type
#readIdentifier:sType
#continue
'{'
// will store enums into this association table
=> local allEnums;
// iterate on enum ids; at least one expected
enum_id(allEnums)
[
','
enum_id(allEnums)
]*
// may end with a single comma!
[',']?
'}'
=> {
// the parsing on this enum has finished.
// Now, let's generate the str2enum function:
@int str2@sType@_enum(const char* name, enum @sType@* val) {
int err = 0;
@
foreach i in allEnums {
if i.first() {
@ @
} else {
@ else @
}
@if (strcmp(name, "@i@") == 0) *val = @i@;
@
}
@ else err = -1;
return err;
}
@
}
]
]*
;
enum_id(allEnums : node) ::=
#readIdentifier:sEnum
=> insert allEnums[sEnum]= sEnum;
// don't care about the value, if any
['=' [~[',' | '}']]*]?
;
Then run the command line:
codeworker -translate str2enum.cwp yourCFileWithEnums.c functions.c