如何將列舉型別變數轉換成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-7月-2019

447次瀏覽

啟動你的 事業

透過完成課程獲取認證

入門
廣告
© . All rights reserved.