如何將 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.