Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How to print an enumerator as a string, not an int?

enumerator int print String
0
Posted

How to print an enumerator as a string, not an int?

0

Given an enum, it is easy enough to emit the values of the enumerators or of variables of the enumeration: G:\tmp>type enumvals.c #include typedef enum colors { red, orange, yellow, green, blue, indigo, violet } colors; int main() { colors c = violet; /* Need enum colors in C */ printf(“%d\n”, yellow); printf(“%d\n”, c); return 0; } G:\tmp>como enumvals.c Comeau C/C++ 4.3.4.1 (Mar 30 2005 22:54:12) for MS_WINDOWS_x86 Copyright 1988-2005 Comeau Computing. All rights reserved. MODE:strict errors C++ G:\tmp>aout 2 6 A question comes up surprisingly often though: How do I get the string values that these numbers represent? IOWs, as 2 is yellow, how can I get to see yellow output and not the unhelpful (in some case) 2? Well, there is no direct language support in C and C++ for obtaining the name of an enumerator value. Instead, you need to do something such as: #include typedef enum colors { red, orange, yellow, green, blue, indigo, violet, maxcolors } colors; void emitc

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123