c++cpreprocessoransi-c

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 something 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 if that is the most beautiful way to do it. Is it possible at all?


Solution

  • 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.