How to get enum identifier name as text during runtime?

Is there any preprocessor directive to get the text string of the enum
identifier name
at runtime?
For example, assume:
enum MyList {Mem1, Mem2};

during runtime my code wants to reference Mem1 and print its source
code
text name "Mem1" by referencing Mem1, and not its numeric value 0.

0
guuwwe (5)
4/27/2008 7:06:18 PM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
522 Views

Similar Articles

[PageSpeed] 56

On Sun, 27 Apr 2008 12:06:18 -0700 (PDT), guuwwe@hotmail.com wrote:

>Is there any preprocessor directive to get the text string of the enum
>identifier name
>at runtime?
>For example, assume:
>enum MyList {Mem1, Mem2};
>
>during runtime my code wants to reference Mem1 and print its source
>code
>text name "Mem1" by referencing Mem1, and not its numeric value 0.

You will have to do that yourself. One way is to maintain an array of
strings in parallel to the enum containing the names as text.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
4/27/2008 7:14:57 PM
If you are doing this a lot, you can come up with some macros to do it

For example

#define MYLIST_VALUES() VALUE_(Mem1), VALUE_(Mem2) 

#define VALUE_(x) x
enum MyList {MYLIST_VALUES}
#undef VALUE_
#define VALUE_(x) _T(#x)
LPCTSTR MyListNames[] = { MYLIST_VALUES };
#undef VALUE_

which works if you use the default assignments but not if you want the enums to have
specific values.
				joe
On Sun, 27 Apr 2008 12:06:18 -0700 (PDT), guuwwe@hotmail.com wrote:

>Is there any preprocessor directive to get the text string of the enum
>identifier name
>at runtime?
>For example, assume:
>enum MyList {Mem1, Mem2};
>
>during runtime my code wants to reference Mem1 and print its source
>code
>text name "Mem1" by referencing Mem1, and not its numeric value 0.
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
4/28/2008 1:31:57 AM
On Apr 27, 3:14=A0pm, "Doug Harrison [MVP]" <d...@mvps.org> wrote:
> On Sun, 27 Apr 2008 12:06:18 -0700 (PDT), guu...@hotmail.com wrote:
> >Is there any preprocessor directive to get the text string of the enum
> >identifier name
> >at runtime?
> >For example, assume:
> >enum MyList {Mem1, Mem2};
>
> >during runtime my code wants to reference Mem1 and print its source
> >code
> >text name "Mem1" by referencing Mem1, and not its numeric value 0.
>
> You will have to do that yourself. One way is to maintain an array of
> strings in parallel to the enum containing the names as text.
>
> --
> Doug Harrison
> Visual C++ MVP

You need an array in either case. The enum identifiers have to be
statically bound to their text names by the preprocessor. It is a
simple
thing to have a directive that takes any identifier and assignes its
text name to another identifier or an entry in a constant array,
and a constant array is the only way if you want to keep many
identifiers.

0
guuwwe (5)
4/28/2008 3:16:15 PM
See below...
On Mon, 28 Apr 2008 08:16:15 -0700 (PDT), guuwwe@hotmail.com wrote:

>On Apr 27, 3:14�pm, "Doug Harrison [MVP]" <d...@mvps.org> wrote:
>> On Sun, 27 Apr 2008 12:06:18 -0700 (PDT), guu...@hotmail.com wrote:
>> >Is there any preprocessor directive to get the text string of the enum
>> >identifier name
>> >at runtime?
>> >For example, assume:
>> >enum MyList {Mem1, Mem2};
>>
>> >during runtime my code wants to reference Mem1 and print its source
>> >code
>> >text name "Mem1" by referencing Mem1, and not its numeric value 0.
>>
>> You will have to do that yourself. One way is to maintain an array of
>> strings in parallel to the enum containing the names as text.
>>
>> --
>> Doug Harrison
>> Visual C++ MVP
>
>You need an array in either case. The enum identifiers have to be
>statically bound to their text names by the preprocessor. It is a
>simple
>thing to have a directive that takes any identifier and assignes its
>text name to another identifier or an entry in a constant array,
>and a constant array is the only way if you want to keep many
>identifiers.
****
Not sure that the preprocessor has to enter the picture; the binding is actually done by
the compiler.  I posed a solution in which the preprocessor makes it easier to write, but
you can also (if the enums have specific assignments) write a table of the form

struct {
       MyEnumType id, LPCTSTR str} MyEnumNames[] = {
	{ Mem1, _T("Mem1") },
  	{ Mem2, _T("Mem2") },
	{ 0, NULL }
	};

and write

CString MapEnumToName(MyEnumType id)
   {
    for(int i = 0; MyEnumNames[i].str != NULL; i++)
      {
       if(MyEnumNames[i].id == id)
          return MyEnumNames[i].str;
     }
    CString s;
    s.Format(_T("%d"), id);
    return s;
   }

There are many obvious generalizations of this technique.  It is most useful in debugging.

Another solution is

class EnumMapper {
     public:
         CString MapEnumToName(UINT id)
            {
             EnumMap map = GetEnumMap();
             for(int i = 0; map[i].str != NULL; i++)
                 if(map[i].id == id)
                    return map[i].str;
            CString s;
            s.Format(_T("%d"), id);
            return s;
          }
     virtual EnumMap GetEnumMap() PURE;
    }
class MyEnums : public EnumMapper {
	public:
	typedef enum {Mem1, Mem2} MyEnumType;
                DECLARE_ENUM_MAP()
                virtual GetEnumMap() { return map; }
                CString ToString(MyEnumType type) { 
                                return MapEnumToName((UINT)type);
                               }
    };

BEGIN_ENUM_MAP(MyEnums)
      ENUMTYPE(Mem1)
      ENUMTYPE(Mem2)
END_ENUM_MAP

where you have done something like

#define DECLARE_ENUM_MAP()  static EnumMap map;

#define BEGIN_ENUM_MAP(classname) \
           static EnumMap classname::map[] = {

#define END_ENUM_MAP() \
           { 0, NULL } \
         };

#define ENUMTYPE(x) { (UINT)(x),  _T(#x) },

typedef struct { UINT id; LPCSTR str; } EnumMap;

This may not be complete or necessarily syntactically correct, but it is probably a
reasonable sketch for a starting point.

				joe
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
4/28/2008 5:01:58 PM
Reply:

Similar Artilces:

MSCOMCTL.OCX runtime error
I am trying to use an older program (developed probably around 2003/4). When I attempt to run it I get the following message: > > Run-time error '339': > > Component 'MSCOMCTL.OCX' or one of its dependencies not correctly > registered: a file is missing or invalid > I found this website from google, this specific thread: http://forums.techarena.in/vista-help/845481.htm so I decided to try doing what was suggested in that thread. None of the things that were suggested helped, then it mentioned something about dependency walker. I opened the ...

How to change Static Text property in a function?
I want to change Background(forground) Color of a Static Text control in member function. How to do that? sxy7711 wrote: > I want to change Background(forground) Color of a Static Text control in > member function. How to do that? > > See the example in the doc page for OnCtlColor. -- Scott McPhillips [VC++ MVP] ...

i get error 404 not found when trying to download
I'm trying to download nokia pc suite to windows xp to upload gallery onto the computer but get error message404 not found - how can i download this pc suite please -- Krysy Albutt Krysy Albutt wrote: > I'm trying to download nokia pc suite to windows xp to upload gallery > onto the computer but get error message404 not found - how can i > download this pc suite please Care to enlighten us how this pertains to: - 1) Microsoft 2) Publisher 3) Windows If you're having problems downloading from the *NOKIA* site where do you think you should be directing your ...

How to get Calendar to send me reminders
I have changed my e-mail address but for some reason I cannot get Calendar to send reminders to my new address - I think I have carried out all that is necessary to effect the changover but I am not getting reminders sent. Can anyone help please? Is the Calendar Live ID based and accessible at Calendar.live.com ? -- ....winston ms-mvp mail "Dabardevon" wrote in message = news:FDC2B3B2-EDE4-41B1-BFC4-C0F9ED59CFB9@microsoft.com... I have changed my e-mail address but for some reason I cannot get = Calendar to send reminders to my new address - I think I have...

03Excel shldn't chg col hdrs to nos after text to col, keep alpha
2003 EXCEL: After using text-to-columns, column headers change to numbers, the same as the rows. Afterwards, it's difficult to create formulas to work with in the spread sheets, especially when you want to use absolute references. I looked through help but found no relief. The only way I could figure out how to change them back is to close the workbook, open a previous workbook that has alpha across the top, and then reopen the problem workbook. Excel adopts the first spread sheet's view and carries it over to the problem workbook. Save it then. If anyone else knows a keyb...

Some recipients get the attachment, some get winmail.dat
This one has me baffled. We are using Exchange 2000 and Outlook 2000 and have been for 8 months. No previous problems with attachments (.doc, .xls, .jpg). About 2 weeks ago, we started hearing from certain recipients that the attachment wasn't arriving; instead they were getting an unreadable file called winmail.dat. MS says that this is because the sender is using Rich Text to format the email. We have changed the senders to use Plain Text and still have the same problem. If the email is sent to several recipients, some will get the attachment fine, some will not. This didn'...

How to get the CScrollBar's Handle in CTreeCtrl?
Hey,All: I thought I have a problem when I trid to get the CScrollBar's handle from my CTreeCtrl extended handle. Can anybody tell me whether I can get the handle of the CScrollBar from the CTreeCtrl? Thanks in advance! Carl :-| Carl wrote: > Hey,All: > > I thought I have a problem when I trid to get the CScrollBar's handle from > my CTreeCtrl extended handle. > Can anybody tell me whether I can get the handle of the CScrollBar from the > CTreeCtrl? > > Thanks in advance! > Carl > :-| > > Sorry, it is not that simple. The scroll bars that...

A Crystal Beginner
I am using Crystal 9.2.4.77 and have loaded the Crystal enhancements. Now I want to do against the CRM database. What do I do? I thought I would create a data source to the CRM SQLserver, which I did, then connect to it through Crystal Reports. That works, but when I drill down on the AAA_MSCRM database to choose my tables, it shows me dbo as the only option (where did this come from??) and under that are just a few generic tables. No CRM tables. Something's not quite right. What am I missing? file - log on to aps server "KBLawson" <klawson@aetinc.com> wrote in ...

Install driver files with the same name
Hello, We have multiple driver files with the same name which were provided third party. I am looking for a way to install the drivers. Because We want that the each driver are used in different applications. Is there any way to install the drivers without changing their file sames? Taka <Taka@discussions.microsoft.com> wrote: > >We have multiple driver files with the same name which were provided third >party. >I am looking for a way to install the drivers. >Because We want that the each driver are used in different applications. > >Is there ...

Alter position of "Duplicate Receipt" text on receipt
Hi, I'm not too familiar with XML, but I'd really like to be able to move the position of the text "Duplicate Receipt" into the main body of the receipt- below the store address- as opposed to having it as a header and footer. Can anyone help? Thanks. hi Tara, you can do so, Open the receipt.xml file and find there are 2 boolean paramter <SET name="ShowDuplicateBefore" custom="false" description="Show Duplicate At Top" type="vbBoolean"> True </SET> <SET name="ShowDuplicateAfter" custom="true&q...

Cannot get fast forward or fast reverse to work with WMP 11
I am running Vista Home Premium on a HP G 217-EM Notebook which comes pre-installed with Windows Media Player 11. When I play cds and try to fast forward or fast reverse by keeping the fast forward or fast reverse buttons constantly depressed nothing happens. Why is this, and can anyone come up with a solution? Many thanks This doesn't work on my system either, so it's probably just a limitation of WMP. Fast forward and fast reverse should work fine when you rip the CD's to MP3 or WMA files, and play these files instead. Regards -- Tim De Baets http://www....

Get paid while you get online!!
I found a great Internet company - Cashfiesta.com - that has created a product everyone can benefit from. They pay you while you work or play on your computer. All you need to do is keep their software - the FiestaBar=99 - active while you are online. They even pay you when your friends are using their computers. Unlike other companies, Cashfiesta gives you control over how much money you earn. They have an individual payrate based on the number of Special Offers you sign up for. As some of these offers are free, you can increase your payrate up to 33 times without spending a penny. It's...

Can't get auto-update (update) to install
Version: 2008 Operating System: Mac OS X 10.4 (Tiger) Processor: Power PC I've been trying to manually check for updates to Word 2008, and I get a &quot;critical update&quot; notice, asking me to install auto-update. When I try to install it, I cannot. It just keeps repeating the attempt, in an &quot;endless loop.&quot; What to do? <br> Thank you. ...

Spreadsheet getting corrupted
Hello All: I have a relatively large spreadsheet. I am getting errors (see after my signature line). What could be causing these errors? Is it that the spreadsheet is too large? Thanks Deguza -------------------------------------------------------- Microsoft Office Excel File Repair Log Errors were detected in file 'C:\Documents and Settings\deguza\My Documents\sales\Sales_2006_2007.xls' The following is a list of repairs: Global PivotTable report information was repaired due to integrity problems. Global PivotTable report information was repaired due to integrity problems. Glo...

Checking specific text string in excel files stored in a folder
Hi, I need to write a code that can do the following: 1) prompt user to select a particular folder 2) search for a particular text string, for e.g., ABCD in all the excel files in that folder (the number of files in the folder will vary and so does the names of the files). Is it possible to specify the string that we want to search on the fly when macro is run? 3) create a simple report that contains the filename in one column and yes / no in the second column that tell me which file names contain that keyword (it will be great if the path of the file can be recorded in the 3rd colum...

Reg getting the next IV Document Number field !
Hi, I am creating a window in dexterity similar to the item transaction entry window (Transactions>Inventory> Transaction Entry). In the Item transaction Entry window, the Document number field defaults to the next document number when we move the focus to that field. I wanted to know if there is any function , or table that i can access to get the next document number in the new window that i am creating. Thanks, swetha -- swetha >In the Item transaction Entry window, the Document number field defaults to the next document number when we move the focus to that field.< T...

referencing a cell determined by name in another cell
How do I reference a cell within a formula based on the contents of another cell? For example if one cell contained a reference/address for a column array, how could I refer to this cell (and hence the column array) within the vlookup function instead of having to put in the actual table array. In other words an external way of changing the table array rather than going into the formula. VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) Hi use INDIRECT for this -- Regards Frank Kabel Frankfurt, Germany "ricardo wants answers" <ricardo wants answers@discussion...

Get notified when Out of Office is on
I am using Outlook 2007. With 2003, when returning from leave, I used to get a notification that the Outlook out of office was still on and asking me if I wanted to switch it off. This reminder no longer appears with 2007. How can I switch this setting on so that I get the notification? "Mary Ann" <MaryAnn@discussions.microsoft.com> wrote in message news:ED5533A7-D0EA-41B8-B1A0-A9D15FB6FD98@microsoft.com... >I am using Outlook 2007. With 2003, when returning from leave, I used to get > a notification that the Outlook out of office was still on and asking me ...

No mapping between account names and security IDs was done. 11-10-05
"No mapping between account names and security IDs was done. SOAP Server Application Faulted" Removed licenses from other users that are no longer here. I cannot add the new users. any ideas what the error messages mean? ...

How do I get??
Sorry if this seems a fairly easy question to you guys. I have a spreadsheet and I need to get the current system time into a cell. The format of the time is hh:mm am/pm. Any assistance would be most helpful. Hi try =INT(NOW()) in this cell and format is to your needs -- Regards Frank Kabel Frankfurt, Germany PM wrote: > Sorry if this seems a fairly easy question to you guys. > > I have a spreadsheet and I need to get the current system time into a > cell. The format of the time is hh:mm am/pm. > > Any assistance would be most helpful. PM, in the cell you want pu...

Identify Duplicates (Group Records First)
Hello, I have an invoice table that includes the fields CustomerNumber and DivisionNumber. Customers can deal with multiple divisions. CustomerNumber DivisionNumber ABC Co 10 ABC Co 10 ABC Co 10 Smith Inc 10 Smith Inc 10 Jones Corp 20 Jones Corp 20 Jones Corp 10 XYZ Inc 20 XYZ Inc 20 I am trying to come up with a query that will identify that Jones Corp has records in both division 20 and 10. I would like the results ...

Getting Control ID in Active X control
GetWindowLong return 0. You need to call GetDlgCtrlID from outside the activex control as the function available within the control returns an arbitrary value of zero. Take a look at this article http://xendra.ens.uabc.mx/~sinfante/loo/libro/ch17_4.htm particularly the paragraph preceeding the title "MFC and Ambient Properties". This really begs the question why you want the ID in the first place as activex controls have to be fully self containing to operate - with a few exceptions where sibling controls need to be able to locate each other. - Tim "ytv" <...

over VPN, it gets stuck when sending outgoing email
When I use VPN to connect to work from home, the outlook can not finish sending outgoing emails. The progress bar moves to the end but then stops there forever. It can never finish. The receiving of new incoming emails work fine. All other network functionality works, e.g. internet browsing, telnet, ftp, etc, all work fine. My system is win2k. I use linksys wireless DSL router. I'd appreciate any hint! Are you using Exchange server? I'd set up your mail profile to prompt you to work offline or online - when using VPN, work offline with scheduled syncs. If not using exchange, pos...

Get photos from a camera
I have an asp.net intranet application that I need to upload 1 or all photos from a digital camera at a PC workstation. We are using DataGrids and GridViews to display them on the web once they are uploaded but need something at the client. I assume I need some sort of ActiveX process or something. Has anyone run into a solution for this need? Thanks. -- David "DavidC" <dlchase@lifetimeinc.com> wrote in message news:2B061F4F-B548-4AA4-96FA-2F87383192D2@microsoft.com... > I have an asp.net intranet application that I need to upload 1 or all > photos ...

how to get the format of this cell right?
When I let go: Selection.Replace " ", Replacement:="-", Lookat:=xlPart, _ SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False " " is entered by means of an array: Words = Array(" ", "+", "/", "---", "--", "&") on a cell containing: 5 a I would expect to get: 5-a as a result. Unfortunately, it produces 5:00:00-AM. How can I solve this tiny but frustrating problem? best regards Pet...