Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++에서 열거형(Enum)을 문자열로 변환하는 방법

C++에서는 열거형(enum) 데이터를 문자열로 자동 변환해 주는 내장 함수나 연산자가 기본적으로 제공되지 않습니다. 하지만 사용자 정의 함수를 직접 작성하면 충분히 해결할 수 있습니다.

가장 널리 쓰이는 방법은 열거형 값을 인자로 받아, 각 상수에 대응하는 이름을 문자열 형태로 반환하는 함수를 만드는 것입니다. 아래에서 switch 문을 활용한 기본적인 구현 방법을 살펴보겠습니다.

예제 코드

#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 << "동물 : " << enum_to_string(Dog) << ", 번호: " << Dog << endl;
    cout << "동물 : " << enum_to_string(Mouse) << ", 번호: " << Mouse << endl;
    cout << "동물 : " << enum_to_string(Elephant) << ", 번호: " << Elephant;
}

실행 결과

동물 : Dog, 번호: 3
동물 : Mouse, 번호: 5
동물 : Elephant, 번호: 1

동작 원리

enum_to_string() 함수는 전달받은 열거형 값을 switch 문으로 검사하여, 각 상수에 해당하는 이름을 문자열 리터럴로 반환합니다. 모든 케이스에 해당하지 않는 값이 들어올 경우를 대비해 default 블록에서 오류 메시지를 반환하도록 처리했습니다.

열거형 상수는 내부적으로 정수 값(0부터 시작)으로 저장되기 때문에, 출력 결과에서 Dog는 3, Mouse는 5, Elephant는 1로 표시됩니다.

대안: std::map을 이용한 방법

열거형 항목이 많아지면 switch 문이 길어져 관리하기 어려워질 수 있습니다. 이런 경우 std::map으로 매핑 테이블을 미리 만들어 두면 코드가 더욱 간결해집니다.

#include <iostream>
#include <map>
using namespace std;

enum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};

string enum_to_string(Animal type) {
    static const map<Animal, string> m = {
        {Tiger, "Tiger"}, {Elephant, "Elephant"}, {Bat, "Bat"},
        {Dog, "Dog"}, {Cat, "Cat"}, {Mouse, "Mouse"}
    };
    auto it = m.find(type);
    return (it != m.end()) ? it->second : "Invalid animal";
}

두 방식 모두 동일한 결과를 제공하며, 프로젝트 규모와 유지보수 편의성에 따라 적절한 방법을 선택하면 됩니다.