Just wonder is there any way to display enum as enum not as integer?
Thank you.

Not without doing some kind of explicit mapping:

#include <iostream>
#include <string>

enum Color {Red, Blue, Green};

static std::string ToString(Color color)
    switch (color)
        case Red:   return "Red";
        case Blue:  return "Blue";
        case Green: return "Green";
        default: return "";

int main()
    Color color = Red;

    std::cout << ToString(color) << '\n';

Thanx, Tom Gunn.

No need for a case statement. Since you have an enum table and if they use the default sequencing equate 0, 1, 2, etc. then use an ASCII table lookup that matches 0 based enum to table index. You may want to put an assertion on runtime to make sure the highest enum has an ASCII equivalent in the table!

I personally like enum's to stand out!

typedef enum 
    iCOLOR_RED = 0,
       // Insert new enums above this line

char *szColorTbl[] = 
const uint nColorTblCount = sizeof(szColorTbl) / sizeof(char *);

iCOLOR hue;

assert( nColorTblCount == iCOLOR_MAX );

No need for a case statement.

If you add a bunch of restrictions to make table lookup work. ;) Both ways are valid, and it depends on the situation. It is not uncommon for the values in an enumeration to span a large range and be very sparse within that range. Table lookups are not as attractive in that case.

Anyway, thank you for giving another example of explicitly mapping strings to enumerations. I assumed that one simple example would be enough to get the creative juices flowing, but I have been wrong before.

Not a problem. As I mentioned the table lookup only works out if a sequential set of enums is used. Then the case statement is the better selection.

Having posted here, means trying to teach about multi-table lookups in conjunction with case statements is too complicated a concept so I didn't mention it!

And of course case is a tad safer by merely inserting the default! With a table lookup and extra conditional check has to be made to make sure the source value being referenced is valid and not out of range thus invalid!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.