Click here to Skip to main content
Click here to Skip to main content

Converting C++ enums to strings

By , 27 May 2005
 

Introduction

This code is used to convert a C++ enumeration value to its equivalent string representation. It is useful, for example, to debug your code, or generate trace messages.

Using the code

Create a header file called "EnumToString.h" with the following contents:

// File name: "EnumToString.h"
#undef DECL_ENUM_ELEMENT
#undef BEGIN_ENUM
#undef END_ENUM

#ifndef GENERATE_ENUM_STRINGS
    #define DECL_ENUM_ELEMENT( element ) element
    #define BEGIN_ENUM( ENUM_NAME ) typedef enum tag##ENUM_NAME
    #define END_ENUM( ENUM_NAME ) ENUM_NAME; \
            char* GetString##ENUM_NAME(enum tag##ENUM_NAME index);
#else
    #define DECL_ENUM_ELEMENT( element ) #element
    #define BEGIN_ENUM( ENUM_NAME ) char* gs_##ENUM_NAME [] =
    #define END_ENUM( ENUM_NAME ) ; char* GetString##ENUM_NAME(enum \
            tag##ENUM_NAME index){ return gs_##ENUM_NAME [index]; }
#endif

Put your enum in a specific header file using a special syntax. For example, the enum:

enum Days
{
   sunday,
   monday,
   tuesday,
   wednesday,
   thursday,
   friday,
   saturday
};

will become a header file called "Days.h" with the following contents:

// File name: "Days.h"
#if ( !defined(DAYS_H) || defined(GENERATE_ENUM_STRINGS) )

#if (!defined(GENERATE_ENUM_STRINGS))
    #define DAYS_H
#endif

#include "EnumToString.h"

///////////////////////////////
// The enum declaration
///////////////////////////////
BEGIN_ENUM(Days)
{
    DECL_ENUM_ELEMENT(sunday),
    DECL_ENUM_ELEMENT(monday),
    DECL_ENUM_ELEMENT(tuesday),
    DECL_ENUM_ELEMENT(wednesday),
    DECL_ENUM_ELEMENT(thursday),
    DECL_ENUM_ELEMENT(friday),
    DECL_ENUM_ELEMENT(saturday)
}
END_ENUM(Days)

#endif // (!defined(DAYS_H) || defined(GENERATE_ENUM_STRINGS))

Include the file "Days.h" everywhere you need the enum Days. Use it like a normal enumeration:

#include "Days.h"

void MyFunction( Days day )
{
    CString message;
    switch( day )
    {
        case monday:
        case tuesday:
        case wednesday:
        case thursday:
        case friday:
        {
            message.Format("Today is %s, I have to work!", 
                           GetStringDays(day) );
        }
        break;

        case saturday:
        case sunday:
        {
            message.Format("Today is %s, very nice!!!", 
                           GetStringDays(day) );
        }
        break;
    }
    AfxMessageBox(message);                       
}

Create a CPP module where the strings associated to enums are actually defined:

// File name: "EnumToString.cpp"

/// The strings associated with the enums are gererated here
/////////////////////////////////////////////////////////////////////
#define GENERATE_ENUM_STRINGS  // Start string generation
#include "Days.h"             
#include "OtherEnum.h"
#include "AnotherOne.h"
#undef GENERATE_ENUM_STRINGS   // Stop string generation

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Marcos F. Cardoso
Web Developer
Brazil Brazil
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionString to enum Pinmemberjens_weller8-May-12 21:43 
Is it also possible to give an String end get the value of the enum?
GeneralMaking it compile on Linux PinmemberIshmagel29-Jan-09 21:59 
Hi
 
Awesome code! Works like a charm Smile | :)
 
However, when I try to compile it on Linux, I get these errors:
 
error: use of enum `tagDays' without previous declaration
error: ISO C++ forbids declaration of `index' with no type
 
Does anyone know how to fix this?
 
Kind Regards
 
-Kenneth
GeneralA different approach PinmemberHugo González Castro23-Dec-08 17:45 
I have also solved the problem with a different approach, maybe you can find it useful:
http://www.codeproject.com/KB/cpp/ImprovedEnum.aspx[^]
GeneralTry this Pinmembermaddog105-Oct-07 11:44 
http://rssoftware.home.pl/index.php?id=15,0,0,1,0,0
GeneralMaybe you forgotten the most important function! Pinmemberxibeifeijian25-Mar-07 16:51 
Where is GetStringDays???Confused | :confused: Confused | :confused: Confused | :confused: tks
GeneralRe: Maybe you forgotten the most important function! PinmemberHugo GC18-Nov-08 0:29 
GeneralWon't work for enums with specified values PinmemberKaushikSridharan18-Jun-05 9:12 
This is a good idea and useful in most cases. However, it won't work when enums are given specific values, or if they are offset with by a value as in the example below.
 
enum Days {
  monday = 1000,
  tuesday,
  wednesday, 
  ...
};
 
This will cause the GetString function to index beyond the range of the string array.
 
-K
GeneralRe: Won't work for enums with specified values Pinmemberrnadler713018-Apr-06 13:53 
GeneralRe: Won't work for enums with specified values Pinmemberirwin.zuo30-Oct-06 15:50 
GeneralRe: Won't work for enums with specified values PinmemberTroyJ6-Jul-07 10:10 
GeneralRe: Won't work for enums with specified values PinmemberJong Allegraud12-Aug-09 23:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 27 May 2005
Article Copyright 2005 by Marcos F. Cardoso
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid