
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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"; default: 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; }
Output
The Animal is : Dog Its number: 3 The Animal is : Mouse Its number: 5 The Animal is : Elephant Its number: 1
- Related Articles
- How to convert a String to an enum in Java?
- How to enumerate an enum with String type?
- Swift Program to convert int type variable to string
- Swift program to convert double type variable to string
- Swift program to convert string type variable into boolean
- How do we use enum keyword to define a variable type in C#?
- How to define an enumerated type (enum) in C++?
- How to convert the Integer variable to the string variable in PowerShell?
- How to convert a CLOB type to String in Java?
- How to convert string type value to array type in JavaScript?
- How to convert a JSON object to an enum using Jackson in Java?
- How to check if type of a variable is string in Python?
- How to convert a sub class variable into a super class type in Java?
- How to convert a super class variable into a sub class type in Java
- Swift Program to convert int type variable to double

Advertisements