0

How can I access each value of the enum by the index?

for instance,

enum food{PIZZA, BURGER, HOTDOG};

as we all know, the index of the first element starts from 0 unless initialized.

How can I get the string value of the enum from the index?

How can I get it to print the PIZZA?

cout << food(0);

I know it's not correct, but please advise me thanks.

NewbieCoder
  • 676
  • 1
  • 9
  • 32

2 Answers2

0

You can't get the string representation of an enum in c++.

You have to store them somewhere else.

Example

enum food{PIZZA, BURGER, HOTDOG}

char* FoodToString(food foodid)
{
    char* foodStrings[3] = {"PIZZA","BURGER","HOTDOG"};

    return foodstrings[foodid];
}
Vincent
  • 648
  • 3
  • 9
0

There's no way of doing that because there's no need to do that. Generally enums are used to replace integral values we use for example:-

int func () 
{
 //...
if (something )
  return 0;
  return 1;
}

could be replaced with

enum Status { SUCCESS, FAILURE };

Status func () 
{
 //...
if (something )
  return SUCCESS;
  return FAILURE;
}

for better readability.

If you want to get enum value by providing index then you can store index with enum values in some sort of map ( for unordered_map ).

Mafii
  • 7,227
  • 1
  • 35
  • 55
ravi
  • 10,994
  • 1
  • 18
  • 36