Ở đây ta sẽ xem cách ánh xạ một số dữ liệu enum sang chuỗi trong C++. Không có hàm trực tiếp làm điều này. Nhưng ta có thể tự tạo hàm chuyển enum sang string.
Ta sẽ tạo hàm nhận giá trị enum làm đối số, và thủ công trả về tên enum dưới dạng chuỗi từ hàm đó.
Ví dụ mã
#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;
}
Kết quả
The Animal is : Dog Its number: 3 The Animal is : Mouse Its number: 5 The Animal is : Elephant Its number: 1