-1

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
  • 666
  • 7
  • 31

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
  • 628
  • 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
  • 6,734
  • 1
  • 37
  • 54
ravi
  • 10,736
  • 1
  • 14
  • 33