Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

How to convert an enum type variable to a string in C++?


ที่นี่เราจะดูวิธีแปลง enum type data เป็น string ใน C++ ไม่มีฟังก์ชันโดยตรงที่ทำได้ แต่เราสามารถสร้างฟังก์ชันของตัวเองเพื่อแปลง enum เป็น string ได้

เราจะสร้างฟังก์ชันที่รับ enum value เป็น argument และเรา return enum names เป็น string จากฟังก์ชันนั้นด้วยตนเอง

ตัวอย่างโค้ด

#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