在这里,我们将看到如何在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