여기에서는 C++에서 일부 열거형 데이터를 문자열에 매핑하는 방법을 볼 것입니다. 그렇게 하는 직접적인 기능은 없습니다. 하지만 enum을 문자열로 변환하는 자체 함수를 만들 수 있습니다.
열거형 값을 인수로 사용하는 함수를 만들고 열거형 이름을 해당 함수의 문자열로 수동으로 반환합니다.
예시 코드
#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