Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to convert std::string to/from enum class [duplicate]

For the assignment I'm currently working on, I have defined an enum class for differing class semesters.

enum class Semester {
        FALL,
        SPRING,
        SUMMER
};

In my overloaded << operator, I am to print out the lowercase string equivalent of Semester type. I've done so by creating a map with Semester keys and std::string pairs as such:

std::map<Semester, std::string> to_string
{
        {Semester::FALL, "fall"},
        {Semester::SPRING, "spring"},
        {Semester::SUMMER, "summer"}
};

std::stream& operator <<(std::stream& ost, enum Semester semester)
{
        return ost << ::to_string[semester];
}

Already unsure if the previous solution was optimal, I moved onto the next task which was defining Semester load_semester(std::istream& ist). This function receives input from the user as std::string (figuring I'd use std::getline()) and converts it to Semester type. I imagine I could use a map similar to before albeit reversed, but I was curious what a 'proper' way to approach this problem would be.

EDIT: I appreciate the feedback! I will be implementing functions as @casey suggested.

I am implementing enum classes for both semesters and sections (i.e. MATH, READING, SCIENCE, etc.) I will possibly be required to implement more in the future. Could I implement these functions in such a way that I could reuse them?

like image 365
typoplasm Avatar asked Mar 02 '26 18:03

typoplasm


1 Answers

Don't bother with a std::map, just use a function:

//As an aside, avoid uppercase enum names
enum class Semester {
    Fall,
    Spring,
    Summer
};

std::string to_string(const Semester& s) {
    switch(s) {
        case Semester::Fall: return "fall";
        case Semester::Spring: return "spring";
        case Semester::Summer: return "summer";
        default: throw std::exception("to_string: Semester enum values have changed.");
    }
}

Semester from_string(std::string str) {
    std::transform(std::begin(str), std::end(str), std::begin(str), [](unsigned char c)->unsigned char { return std::tolower(c); });
    if(str == "fall") {
        return Semester::Fall;
    } else if(str == "spring") {
        return Semester::Spring;
    } else if(str == "summer") {
        return Semester::Summer;
    } else {
        throw std::exception("from_string: Semester enum values have changed.");
    }
}

std::ostream& operator<<(std::ostream& ost, const Semester& semester) {
    ost << to_string(semester);
    return ost;
}
like image 99
Casey Avatar answered Mar 04 '26 08:03

Casey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!