如何在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 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语