1

I am having a file of strings by which I want to create an enum with values named by the strings. For example the list is:

"a" "b" "c" "d" ...

I would like to get an enum like this

enum SomeEnum { a, b, c, d };

Thanks.

sloth
  • 99,095
  • 21
  • 171
  • 219
mihajlv
  • 2,275
  • 4
  • 36
  • 59
  • 1
    Do you mean that you want to generate C source code for an enum, or that you want to generate an enum at runtime? The former is easy if you know how to read and write files, the latter is not possible. If it is the former, please specify what you're having trouble with. – interjay Jun 14 '12 at 08:28
  • I think that would work, I could just write out a .h file with the enum in it. Thanks. – mihajlv Jun 14 '12 at 08:32
  • This sort of question has already been asked many times before: possible duplicate of [How to convert enum names to string in c](http://stackoverflow.com/questions/9907160/how-to-convert-enum-names-to-string-in-c) – Jens Gustedt Jun 14 '12 at 09:48

3 Answers3

2

I suggest that you use any of the popular scripting languages (perl, python, tcl) and parse the file and generate enums that you like.

sloth
  • 99,095
  • 21
  • 171
  • 219
Bo.
  • 2,547
  • 3
  • 24
  • 36
2

You could use X-Macros, then you only need to place your enum/string in the myfile.h.

myFile.h

#ifndef ENUM_CONVERT
#define ENUM_CONVERT(val)  val
#define ENUM_HEADER enum SomeEnum
#endif

ENUM_HEADER
{
ENUM_CONVERT(a),
ENUM_CONVERT(b),
ENUM_CONVERT(c),
ENUM_CONVERT(d)
};

myFile.c

#include "myFile.h"  // This declares the enum
#define MKSTR(a)           #a
#define ENUM_CONVERT(val)  MKSTR(val)
#define ENUM_HEADER        char *myStrList[]=
#include "myFile.h"  // This defines the stringList
jeb
  • 78,592
  • 17
  • 171
  • 225
0

It is difficult in c to convert string into a variable

Riskhan
  • 4,434
  • 12
  • 50
  • 76