Open In App

How to Convert an Enum to a String in C++?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to Convert an Enum to a String
#include <iostream>
#include <map>
using namespace std;
  
// Define an enumeration named Color with constants RED,
// GREEN, and BLUE
enum Color { RED, GREEN, BLUE };
  
// Create a mapping from Color enum values to corresponding
// strings
map<Color, string> colorToString = { { RED, "Red" },
                                     { GREEN, "Green" },
                                     { BLUE, "Blue" } };
  
// Function to convert a Color enum value to its string
// representation
string enumToString(Color color)
{
    return colorToString[color];
}
// Driver Code
int main()
{
    // Declare a variable 'myColor' and assign it the value
    // GREEN
    Color myColor = GREEN;
  
    // Display the string representation of the enum using
    // the conversion function
    cout << "Color: " << enumToString(myColor) << endl;
  
    return 0;
}


Output

Color: Green

Time Complexity: O(1)
Space Complexity: O(N), N is the number of items in the enum.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads