如何將 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP