C : Printing Enum Values in Text Format
In the realm of programming, enumerations (enums) are often employed to assign numeric values to distinct states or categories. However, when dealing with enums, it becomes necessary to convey their values in a more meaningful textual format for improved readability and understanding.
The Problem: Translating Enum Values to Text
Consider an enum defined as follows:
enum Errors { ErrorA = 0, ErrorB, ErrorC, };
Now, let's attempt to print the value of an enum variable:
Errors anError = ErrorA; std::cout << anError; // Will print "0" instead of "ErrorA"
The challenge here lies in converting the numeric value of the enum into its corresponding text representation.
Solutions Without Using Switch/If
1. Using a Map:
One approach involves utilizing a map to establish a correspondence between enum values and their text representations:
#include <map> #include <string_view> // Create a map that associates enum values with string views std::map<Errors, std::string_view> errorTextMap = { {ErrorA, "ErrorA"}, {ErrorB, "ErrorB"}, {ErrorC, "ErrorC"}, }; // Overload the << operator to handle enum values std::ostream& operator<<(std::ostream& out, const Errors value) { return out << errorTextMap[value]; }
2. Using an Array of Structures with Linear Search:
An alternative solution involves creating an array of structures:
#include <string_view> // Define a structure to store enum values and text representations struct MapEntry { Errors value; std::string_view str; }; // Create an array of structures containing the mapping const MapEntry errorTextEntries[] = { {ErrorA, "ErrorA"}, {ErrorB, "ErrorB"}, {ErrorC, "ErrorC"}, {ErrorA, 0} // Dummy entry to terminate the search }; // Overload the << operator to handle enum values std::ostream& operator<<(std::ostream& out, const Errors value) { const char* s = nullptr; for (const MapEntry* i = errorTextEntries; i->str; i++) { if (i->value == value) { s = i->str; break; } } return out << s; }
Test the Solutions:
To demonstrate the functionality of the proposed solutions:
#include <iostream> int main() { std::cout << ErrorA << std::endl; std::cout << ErrorB << std::endl; std::cout << ErrorC << std::endl; return 0; }
Output:
ErrorA ErrorB ErrorC
The above is the detailed content of How Can I Print C Enum Values as Human-Readable Text Without Using Switch/If Statements?. For more information, please follow other related articles on the PHP Chinese website!