473,406 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

match enum to char* ?

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?

Thanks,
Randy

Nov 14 '05 #1
6 4627

randy1200 wrote:
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?

Thanks,
Randy


No.

Nov 14 '05 #2
randy1200 <ra*******@yahoo.com> wrote:
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?


There are optimizations, but effectively you must do something similar to...

#include <string.h> /* strncmp */

#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)

enum yo { ONE, TWO, THREE };

#define ENUM(name) {STRINGIFY(name),sizeof STRINGIFY(name) - 1,name}

const struct yo_enum {
const char *name;
size_t len;
size_t code;
} enum_map[] = {
ENUM(ONE),
ENUM(TWO),
ENUM(THREE)
};

int str2enum(enum yo *code, const char *name, size_t len) {
const struct yo_enum *pos, *end;

pos = enum_map;
end = pos + (sizeof enum_map / sizeof *enum_map);

for (; pos < end; pos++) {
if (pos->len == len && 0 == strncmp(pos->name,name,len)) {
*code = pos->code;
return 1;
}
}

return 0;
}
Nov 14 '05 #3
randy1200 wrote:
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? cat main.c #include <stdio.h>
#include <string.h>

enum yo { ONE, TWO, THREE };
const
char* const yoString[] = { "ONE", "TWO", "THREE" };

int main(int argc, char* argv[]) {
if (1 < argc) {
char* test = argv[1];
for (enum yo j = ONE; j <= THREE; ++j)
if (0 == strcmp(yoString[j], test))
fprintf(stdout, "yoString[%d] = %s\n", j, yoString[j]);
}
else {
fprintf(stderr, "usage: %s [ONE|TWO|THREE]\n", argv[0]);
}

return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main usage: ./main [ONE|TWO|THREE] ./main ZERO
./main ONE yoString[0] = ONE ./main TWO yoString[1] = TWO ./main THREE

yoString[2] = THREE

Nov 14 '05 #4
"randy1200" <ra*******@yahoo.com> wrote in message news:<26******************************@localhost.t alkaboutprogramming.com>...
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
Nov 14 '05 #5
Hum! About my CodeWorker's script: I forgot to remove the line 13,
which I needed for debug. Please remove it (this line is unindented
and is worth '#continue').
Nov 14 '05 #6
Many thanks for the excellent coding tips! This really helps me out...

Randy

Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Rafal 'Raf256' Maj | last post by:
Hi, how can I make operator that will automaticly converse tMyEnum into char, typedef enum { ... } tMyEnum; void Fun(char c) { ... } tMyEnum e; Fun( e );
9
by: AngleWyrm | last post by:
"The C++ Programming Language" by Bjarne Stroustrup, copyright 1997 by AT&T, section 4.8 (pp 77): "A value of integral type may be explicitly converted to an enumeration type. The result of such a...
2
by: Voronkov Konstantin | last post by:
Thank you for answer, but I still did not got *how* to make serialization of enum type. Can you provide more instructions or hint, please? My task is to serialize enum to something like byte...
2
by: randy1200 | last post by:
I've received the following: typedef enum { 10Hz, 100Hz } myfreq_t; So in my code, if I say: myfreq_t f; f = 10Hz; //f = 0, as expected If I say:
18
by: Nebula | last post by:
Consider enum Side {Back,Front,Top,Bottom}; enum Side a; Now, why is a = 124; legal (well it really is an integer, but still, checking could be performed..) ? Wouldn't enums be more useful if...
4
by: adrian suri | last post by:
Hi playing with enum, for example system DosCall return int values for disk partition so say I use an enum #include <iostream> using namespace std; int main() {
10
by: kar1107 | last post by:
Hi all, Can the compiler chose the type of an enum to be signed or unsigned int? I thought it must be int; looks like it changes based on the assigned values. Below if I don't initialize...
7
by: Travis | last post by:
Just curious, which takes less memory? enum Months { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; static const char *Months =
16
by: andreyvul | last post by:
If I try compiling this in gcc, it says: "error: request for member `baz' in something not a structure or union". Any workarounds or tips on how to make a structure such that it behaves like an...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.