Convert enum to string in C++

Enum to String in C++

There are a variety of methods to convert enum to String in C++. In this article, we will discuss some of the efficient and easy ways to convert enum to string.

enum is a user-defined data type that contains integral constants. We use the keyword ‘enum’ to define it.
Example:

Here the name of the enum is languages and {Java, CPP, Python, Ruby} are values of type enum. By default, Java is 0, CPP is 1 and so on. The default values can also be changed at the time of declaration like this:

Let’s check the ways to convert enum to String in C++:

Using stringify macro method to convert enum to String in C++

It is a better way to convert an enum and it works in most of the cases. stringify() macro can be used to convert text in the code into a string. In this method, no variable dereferencing or macro substitutions are not required.
Note: This method can convert only the exact text which is mentioned inside the parentheses.
For example:

Code

Output

Elements in the enum are:
java
python
cpp
Ruby

Using const char* Array to convert enum to String in C++

It is the simplest way to convert an enum. In this method we will use the default values of enum to access the elements in the string array. This method can also be called the most naive method.
Code

Output

Java
Python
Ruby
C++

Using a custom-defined function to convert enum to String in C++

Code

Output

Java
Python
Ruby
C++

Conclusion

We discussed different methods to convert enum to string. First method has the capability to handle big enums as well and other methods can be used for a simple conversion. Third party libraries can also be used to convert an enum to a string like this.
Happy Learning!!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *