psihodelia psihodelia - 1 year ago 84
C Question

How to convert an enum type variable to a string?

How to make printf to show the values of variables which are of an enum type? For instance:

typedef enum {Linux, Apple, Windows} OS_type;
OS_type myOS = Linux;

and what I need is smth. like

printenum(OS_type, "My OS is %s", myOS);

which must show a string "Linux", not an integer.

I suppose, first I have to create a value-indexed array of strings. But I don't know what is the most beautiful way to do it. Is it possible at all?

Answer Source

There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.

If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download