How to Convert an Enum to a String in C++?
Last Updated :
21 Feb, 2024
In C, an enumeration is a user-defined data type whose members can be assigned some integer values. In this article, we are going to discuss how to convert an Enum to a String in C++.
Example:
Input:
myColor = GREEN;
Output:
Green
Convert an Enum to a String in C++
There are various methods to convert an enum to a string. A typical practice to convert an enum into a string is creating the mapping between values of enums and their string representations.
Approach
- Define an enum that represents a collection of related constants, assigning each constant a meaningful name.
- Use map to create a connection between enum values and their corresponding string representations.
- Establish a clear association between each enum value and its corresponding string by populating the mapping data structure.
- Develop a function that takes an enum value as input and returns its associated string by referencing the established mapping.
- Return the corresponding string from the function based on the enum parameter.
C++ Program to Convert an Enum to a String
C++
#include <iostream>
#include <map>
using namespace std;
enum Color { RED, GREEN, BLUE };
map<Color, string> colorToString = { { RED, "Red" },
{ GREEN, "Green" },
{ BLUE, "Blue" } };
string enumToString(Color color)
{
return colorToString[color];
}
int main()
{
Color myColor = GREEN;
cout << "Color: " << enumToString(myColor) << endl;
return 0;
}
|
Time Complexity: O(1)
Space Complexity: O(N), N is the number of items in the enum.
Share your thoughts in the comments
Please Login to comment...