C++

C++ Ways to Convert Enum to String

A data type that may be assigned a list of values is known as an enumerated type (enum). The user specifies the values for it when an enumerated type is declared. The compiler throws an error when we assign a float value to a character value. Similarly, attempting to allocate any other value to the specified data types results in an error from the compiler. Values of the enumerator type are sometimes known as enumerators. It, too, is allocated a value of zero, just like the array.

Enum is a data type that may be specified by the user that contains integral constants. To define it, we utilize the modifier ‘enum’. In this article, we will look at how to transfer certain enum type values to a string in C++. Converting an enum to a String can be achieved in various ways. We will go through some of the most efficient and simple methods for converting an enum to a string. This method represents a collection of integer numbers in a less error-prone and more readable manner.

Example 1: Use of stringify() method to convert enum to string in c++:

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

Let’s demonstrate the code implementation. In the first step, we have imported two standard files in the header section. The first is the iostream file and the second one is the define stringify file which passes an argument in it. This file converts macro arguments to string literals without extending the parameter name. The namespace std file is also included for utilization of its functions.

Then, we have defined an enum class as a “universe” and it contains four different values of type enum. Here, we have the first enum value at position 0,the second enum value at position 1, and so on, by default. Now, we have a character data type class as “Convert_enum[]” where we called stringify method. The stringify method takes values of enum type and converts them into a string.

We have created a function as “displayitems” which will print the values stored in the enum class. In the end, we have invoked the main function which is calling the function “displayitems” and taking the enum class “universe” as an argument. The enum type’s value will be converted to a string using this method.

#include<iostream>

#define stringify( name ) #name

using namespace std;

enum Universe {
  Earth =0,
  Water,
  Air,
  Fire
};

const char* convert_enum[] = {
  stringify( Earth ),
  stringify( Water ),
  stringify( Air ),
  stringify( Fire )
};

void displayitems( Universe item ){
  cout<<convert_enum[ item ] <<endl;
}

int main(){

  cout<< "Enum items are: "<<endl;
  displayitems((Universe)0);
  displayitems((Universe)1);
  displayitems((Universe)2);
  displayitems((Universe)3);
  return 0;
}

The items containing the enum class are shown in the following image and are converted into the string:

Example2: Use of constant char* array to convert enum to string in c++:

Using const char* array is one of the most basic methods for converting an enum. To access the elements of the string array, we will utilize the default values of enum in this method.

Initially, we have standard header files in the header section of the following program. We have a namespace std file too for accessing its function. Then, we have defined an enum class by using the enum keyword along with the class name. The class name is represented as “datatypes”. The enum class “datatypes” contains the four elements.

After that, we have a const char pointer array as “enumStr” that contains the string values from an enum type. Thus, “enumStr[]” is a string array that cannot be modified. Then, we have the main function and in the main function, we have a cout command which takes the values of string array “enumStr” and will print on the prompt screen.

#include <iostream>
#include <string>
using namespace std;

enum datatypes { Integer, String, Char, Float } ;

static const char *enumStr[] =
{ "Integer", "String", "Char", "Float" };

int main(){

  cout<<enumStr[Integer] <<endl;
  cout<<enumStr[String] <<endl;
  cout<<enumStr[Char] <<endl;
  cout<<enumStr[Float] <<endl;

  return 0;
}

The outcome we got by using the const char pointer array in the above program is shown below:

Example 3: Using the defined function to convert enum to string in c++:

We can also implement our function that accepts an integer of enum class as an argument and returns a string as an output.

The program has included the required c++ library in the header along with the std namespace file. After this, we have created an enum with the “enum” modifier. The enum is defined with the name “Animal”. The “Animal” stores five random values of an enum type. We have a const char pointer array as “enum string” in the next line of code. It contains an array of string values.

Then, we have defined a custom function as “ConvertToenum”. This function is taking enum integers as an argument as “val”. The string variable is populated inside the function with a const char* item from the enum string array. In the end, we have defined the main function in which we have called the custom function “convertToenum” and passed the enum values to this custom function.

#include <iostream>
#include <string>
using namespace std;

enum Animals { Bear, Cat, Dog, Goat , Mouse } ;

static const char *enum_string[] = { "Bear", "Cat", "Dog", "Goat" , "Mouse" };

string convertToenum (int val){

    string MyStr(enum_string[val]);
    return MyStr;
}

int main(){

  cout<<convertToenum(Bear) <<endl;
  cout<<convertToenum(Cat) <<endl;
  cout<<convertToenum(Dog) <<endl;
  cout<<convertToenum(Goat) <<endl;
  cout<<convertToenum(Mouse) <<endl;
 
  return 0;
}

The string array generated from the enum type is the outcome of the above code execution shown in the following image.

Conclusion

We have explored many approaches for converting an enum to a string. The first method which is the stringify() method can handle large enums as well, while the other methods may be used for easy conversions. These are quite simple approaches, and with only one attempt, you will be comfortable with them.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content