C++

Elegant Functions to Convert Enum to String in C++

In C++, an enumeration which is commonly referred to as an enum, is a user-defined type that allows you to define a set of named constants. An enum in C++ provides a mechanism to assign symbolic names (enumerators) to integral values which results in a more readable and expressive code.

A string in C++ represents a sequence of characters that are stored in a contiguous block of memory. It is a fundamental data type that is specifically designed to handle a textual data or sequences of characters.

The strings in C++ are dynamic in size, automatically manage the memory allocation, and provide a wide range of operations to work with textual data efficiently.

Converting Enum to String

There are several reasons why you may want to convert an enum to a string in C++. Converting an enum to a string allows you to display the enum value in a human-readable format. When receiving an input from a user or reading a data from a file, it’s often in the form of strings. Converting a string representation of an enum to the corresponding enum value allows you to parse and process the input correctly.

Then, working with data storage or communication protocols, it’s common to convert the data to a string representation for serialization and deserialization. By converting an enum to a string, you can easily represent the enum value in a format that is suitable for storage or transmission and convert it back to the original enum value when needed.

Overall, converting enums to strings in C++ enhances code readability, simplifies the input/output operations, facilitates the data interchange, and improves the user interaction by providing a more meaningful representation of the enum values.

We’ll explain two elegant methods in this article to achieve this conversion in detail.

Method 1: Using a Switch Statement

One approach is to use a “switch” statement to manually convert each enum value to its string representation. We will now demonstrate an example to employ the “switch” statement method to convert an enum to a string in C++.

#include <iostream>

#include <string>

enum class PAINT {

  DULEX,

  NIPPON,

  KANSAI

};

std::string enumToString(PAINT brand) {

  switch (brand) {

   case PAINT::DULEX:

     return "Dulex ";

   case PAINT:: NIPPON:

     return "Nippon";

   case PAINT::KANSAI:

     return "Kansai";

   default:

     return "Unknown";

  }

}

int main() {

  PAINT brand = PAINT::NIPPON;

  std::string brandString = enumToString(brand);

  std::cout << "Paint brand is: " << brandString << std::endl;

  return 0;

}

Let’s go through the code step by step:

The code begins by including the necessary headers – <iostream> and <string> – to work with the input/output operations and strings, respectively.

The PAINT enum class is defined which represents a set of named constants (enumerators) – DULEX, NIPPON, and KANSAI. These constants are scoped within the PAINT enum class.

The enumToString() function is declared which takes the PAINT enum value as an argument and returns a corresponding string representation. It uses a “switch” statement to match the brand parameter with the appropriate case and returns the corresponding string.

In the main() function, a PAINT variable brand is declared and assigned with the PAINT::NIPPON value. This initializes the brand variable with the NIPPON enumerator from the PAINT enum.

The enumToString() function is called, passing the brand variable as an argument. The resulting string format is preserved in the “brandString” variable.

Finally, the program outputs the string representation of the paint brand using the “std::cout” and the “brandString” variable.

Running this program gets us the following:

The string is displayed as “Paint brand is: Nippon”.

This strategy is uncomplicated and simple to comprehend. However, as the number of enum values grows, the “switch” statement can become cumbersome to maintain and is prone to human error. Additionally, it requires modifying the enumToString() function whenever new enum values are added.

Method 2: Using a String Array to Convert an Enum to a String

Another elegant method involves using an array of strings to store the string representations of the enum values. We will create an example to show you how to use a string array in a C++ program to convert an enum to a string.

#include <iostream>

#include <string>

enum class Animal {

  DOG,

  CAT,

  HORSE

};

const std::string enumStrings[] = {

  "Bull",

  "Cat",

  "Horse"

};

std::string enumToString(Animal pet) {

  int index = static_cast<int>(pet);

  if (index < 0 || index >= sizeof(enumStrings) / sizeof(enumStrings[0])) {

    return "Unknown";

  }

  return enumStrings[index];

 }

int main() {

  Animal pet = Animal::CAT;

  std::string enumString = enumToString(pet);

  std::cout << "Animal: " << enumString << std::endl;

  return 0;

}

This code snippet includes the necessary headers – <iostream> and <string> – to work with the input/output operations and strings, respectively.

The program defines an enum class called “Animal” with three enumerators: DOG, CAT, and HORSE. The enumerators represent the different animal types. Then, the program declares a string array named “enumStrings” that holds the string representations of the enum values in the same order as the “Animal” enum declaration. The first string in the array corresponds to “Animal::DOG”, the second string corresponds to “Animal::CAT”, and the third string corresponds to “Animal::HORSE”.

After that, we define the enumToString() function. The enumToString() function provides a clear mapping between the enum values and their respective strings. This program outputs the corresponding string representation for an “Animal” enum value that is input. Inside the function, the static_cast<int>(pet) converts the “Animal” enum value to an integer index. The “if” condition checks if the index is out of the valid range of the “enumStrings” array. If so, it returns “Unknown” as a fallback. If the index is within the valid range, it retrieves the corresponding string representation from the “enumStrings” array and returns it.

In the main() function, we declare an “Animal” variable named “pet” and assign it with the “Animal::CAT” value. It then calls the enumToString() function, passing the pet variable as an argument. The string representation that is returned from this function is stored in the “enumString” variable.

We utilize the “std::cout” to output the string representation of the “Animal” value using the “enumString” variable. Lastly, the return 0 signifies the program’s successful execution.

The resultant snapshot shows the output which is “Animal: Cat”:

This method is more scalable and less error-prone compared to the “switch” statement approach. It makes adding or removing the enum values simple without changing the conversion mechanism. However, it assumes a sequential ordering of the enum values, and care should be taken when modifying the enum declaration.

Conclusion

In C++, an enum can be converted to a string using various techniques. This post covered two of these techniques. The first one is utilizing the “switch” statement to format an enum to a string. We performed a practical illustration to comprehend the “switch” statement usage. For the second demonstration, the string is practiced in a C++ program to retrieve a string representation of defined enum class elements.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.