By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,605 Members | 1,488 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,605 IT Pros & Developers. It's quick & easy.

How to print enums?

P: 13
Hi,

Does enyone know how to print string describing the enum value?
For example:

enum MyEnum{F1=1, F2};
...
MyEnum me = F2;
printf("My Value: %d", me);
...
I get string: "My Value: 2", but how can i format the string to get strong like:
"My Value: F2" ?

Thanks in advance for help?

kenk
Nov 10 '06 #1
Share this Question
Share on Google+
3 Replies


Banfa
Expert Mod 5K+
P: 8,916
There is no short cut
Expand|Select|Wrap|Line Numbers
  1. if (me == F2)
  2. {
  3.     printf("My Value: F2");
  4. }
  5. else if (me == F2)
  6. {
  7.     printf("My Value: F1");
  8. }
  9. else
  10. {
  11.     printf("My Value: Invalid Enum Value");
  12. }
  13.  
When using enums I often implement a function that returns const char * to convert the enum value to a string of it's name to make it easily accessable for debug messages.
Nov 10 '06 #2

Ganon11
Expert 2.5K+
P: 3,652
Expand|Select|Wrap|Line Numbers
  1. if (me == F2)
  2. {
  3.     printf("My Value: F2");
  4. }
  5. else if (me == F2)
  6. {
  7.     printf("My Value: F1");
  8. }
  9. else
  10. {
  11.     printf("My Value: Invalid Enum Value");
  12. }
  13.  
This will work, but if you want to save some typing, use a switch structure:

Expand|Select|Wrap|Line Numbers
  1. switch(me) {
  2.    case F1: printf("My Value: F1"); break;
  3.    case F2: printf("My Value: F2"); break;
  4.    default: printf("My Value: Invalid Enum Value");
  5. }
Nov 10 '06 #3

Banfa
Expert Mod 5K+
P: 8,916
This will work, but if you want to save some typing, use a switch structure:
Quite and in fact particularly true if the enum has >>>2 values
Nov 10 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.