如何将 C++ 枚举映射到字符串?


我们将在此了解如何将一些枚举类型数据映射到 C++ 中的字符串。没有这样的直接函数能做到这一点。但是,我们可以创建我们自己的函数,将枚举转换成字符串。

我们将创建一个将枚举值作为参数的函数,并且我们手动将枚举名称作为该函数的字符串返回。

示例代码

运行演示

#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;
}

输出

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

更新日期:30-Jul-2019

3K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.