How to convert an enum type variable to a string in C++?

Here we will see how to convert some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string.

We shall create a function that takes an enum value as an argument, and we manually return the enum names as a string from that function.

Example Code

 Live Demo

#include <iostream>
using namespace std;

enum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};

string enum_to_string(Animal type) {
   switch(type) {
      case Tiger:
         return "Tiger";
      case Elephant:
         return "Elephant";
      case Bat:
         return "Bat";
      case Dog:
         return "Dog";
      case Cat:
         return "Cat";
      case Mouse:
         return "Mouse";
         return "Invalid animal";

int main() {
   cout << "The Animal is : " << enum_to_string(Dog) << " Its number: " << Dog <<endl;
   cout << "The Animal is : " << enum_to_string(Mouse) << " Its number: " << Mouse << endl;
   cout << "The Animal is : " << enum_to_string(Elephant) << " Its number: " << Elephant;


The Animal is : Dog Its number: 3
The Animal is : Mouse Its number: 5
The Animal is : Elephant Its number: 1

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started