Home >Backend Development >C++ >How to Retrieve Enum Values as Text in C ?
Retrieving Enum Values as Text in C
In C , the default behavior for printing enums is to output their numerical values. However, there are situations where it is desirable to retrieve the textual representation of an enum value.
Solutions Without if/switch:
Using a Map:
#include <map> #include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator result; #define INSERT_ELEMENT(p) result.emplace(p, #p); INSERT_ELEMENT(ErrorA); INSERT_ELEMENT(ErrorB); INSERT_ELEMENT(ErrorC); #undef INSERT_ELEMENT return result; }(); return out <p><strong>Using an Array with Linear Search:</strong></p> <pre class="brush:php;toolbar:false">#include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operatorstr; i++) { if (i->value == value) { s = i->str; break; } } return out <p><strong>Using a Switch/Case Statement:</strong></p> <pre class="brush:php;toolbar:false">#include <string> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator<p><strong>Test Case:</strong></p> <pre class="brush:php;toolbar:false">#include <iostream> int main() { std::cout </iostream>
The above is the detailed content of How to Retrieve Enum Values as Text in C ?. For more information, please follow other related articles on the PHP Chinese website!