473,625 Members | 2,668 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4670

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*******@yaho o.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*******@yaho o.com> wrote in message news:<26******* *************** ********@localh ost.talkaboutpr ogramming.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(con st 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(c onst 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(allEnum s)
[
','
enum_id(allEnum s)
]*
// may end with a single comma!
[',']?
'}'
=> {
// the parsing on this enum has finished.
// Now, let's generate the str2enum function:
@int str2@sType@_enu m(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(allEnum s : node) ::=
#readIdentifier :sEnum
=> insert allEnums[sEnum]= sEnum;
// don't care about the value, if any
['=' [~[',' | '}']]*]?
;

Then run the command line:
codeworker -translate str2enum.cwp yourCFileWithEn ums.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
2248
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
3127
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 conversion is undefined unless the value is within the range of the enumeration. For example: enum flag { x=1, y=2, z=4, e=8 }; // range 0:15 flag f1 = 5; // type error: 5 is not of type flag flag f2 = flag(5); // ok: flag(5) is of type flag and...
2
4276
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 array, and then load enum from that byte array to the same enum type on other platform. One way to do I see is:
2
1805
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
2366
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 there was a bit more typechecking ?
4
579
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
23592
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 FOO_STORE to be, say -10, I get a warning about unsigned comparison and I'm seeing an infinite loop. If I do initialize FOO_STORE = -10, I don't see any warnings. No infinite loop.
7
8275
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
6438
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 enum but its members can be addressed with '.'? I don't want to have to do this using #defines, as it would be far too messy. code: static struct { static const int baz = 1; } bar;
0
8251
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8688
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8635
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8352
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7178
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6115
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4085
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2614
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.