- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to map C++ enums to strings?
Here we will see how to map 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 the 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
Advertisements