0

I have an enum and i want to get those enum types in to string in Switch case conditions.

enum WeekEnum
{
Mon = 0;
Tue = 1;
Wed = 2;
}

std::string weekEnumToStr(int n)
{
 std::string s("unknown");
switch (n)
{
case 0: { s = "Mon"; } break;
case 1: { s = "Tue"; } break;
case 2: { s = "Wed"; } break;
}
return s;
}

So in the above i am hardcoding the "Mon" instead is there a way that we get the enum type directly as a string. As currently if i am passing enum type inside switch case i am getting the id either 0 or 1 or 2 but i need Mon/Tue/Wed as a string

  • Are you saying you want to do `enum WeekEnum { Mon = "Mon", Tue = "Tue", Wed = "Wed" };`? That won't work, `enum`s need an integral type. You could, however, use the `enum` in an `std::unordered_map`. Or you could use a lookup table too, perhaps. – mediocrevegetable1 Apr 28 '21 at 04:33
  • no i dont want the value in a string. My requirement is if i pass either 0 or 1 in switch i need to return the enum type. However i can pass the value in quotes "" , but want the exact name in enum – user3064181 Apr 28 '21 at 05:23
  • X-Macros to the rescue? Although macros are persistently blamed for being C's leftover not belonging to contemporary C++, they might be the apt solution. – nvevg Apr 28 '21 at 06:19

1 Answers1

0

You can use some container to map the enum value to a string. For example std::array.

#include <string>
#include <array>
#include <iostream>

enum WeekEnum
{
    Mon = 0,
    Tue = 1,
    Wed = 2
};

std::array<std::string, 3> enumNames{"Mon", "Tue", "Wed"};

std::string weekEnumToStr(unsigned n)
{
    if (n < 3)
    {
        return enumNames[n];
    }
    return "unknown";
}

int main()
{
    std::cout << weekEnumToStr(Tue);
}
super
  • 12,335
  • 2
  • 19
  • 29