如何在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
热门推荐
10 春节后的祝福语简短
11 中考祝福语简短卡片大全
12 公司28 周年祝福语简短
13 祝女性生日祝福语简短
14 简短的出行工作祝福语
15 师姐毕业送花祝福语简短
16 考试祝福语日文简短版
17 5岁宝宝祝福语简短
18 老年 生日祝福语大全简短