Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enum for an array index in c++

Tags:

c++

enums

#include <stdlib.h>
#include <stdio.h>
using namespace std;



void main(){
    char *resolutions[] = { "720x480", "1024x600", "1280x720", "1920x1080" };

    int x = 0;

    enum ResMode
    {
        p480,
        p600,
        p720,
        p1080
    }; 
    ResMode res = p480;

    printf("\nPlease enter the resolution you wish to use now by entering a number");
    printf("\n480p[0], 600p[1], 720p[2], 1080p[3]");
    gets(res);

    printf("\nThe resolution you have selected is %s", resolutions[res]);

}

so basically i want to be able to press 1 and have it select p600 from enum and out put it as 1024x600 in the next line. I am getting a type conversion error. How can i fix this?

like image 764
Jenna R Avatar asked Jan 28 '26 03:01

Jenna R


2 Answers

Looks like you want to associate some items with other items. Usually associations are described in lookup tables or maps.

std::map<ResMode, std::string> map_table =
{
  {p480,     string("720x480")},
  {p600,     string("1024x600")},
  {p720,     string("1280x720")},
  {p1080,    string("1920x1080")},
};

int main(void)
{
  cout << map_table[p480] << "\n";
  return EXIT_SUCCESS;
}

Likewise, you can map menu selections to enums.

Edit 1

std::map<unsigned int, ResMode> selection_map =
{
  {0, p480}, {1, p600}, {2, p720}, {3, p1080},
};

int main(void)
{
  cout << "\n"
       << "Please enter the resolution you wish to use now by entering a number\n"
       <<"480p[0], 600p[1], 720p[2], 1080p[3]";
  unsigned int selection = 0;
  cin >> selection;
  if (selection < 4)
  {
    Resmode resolution_index = selection_map[selection];
    cout << "You chose: "
         << map_table[resolution_index]
         << "\n";
  }
  return EXIT_SUCCESS;
}
like image 108
Thomas Matthews Avatar answered Jan 30 '26 16:01

Thomas Matthews


int's are not implicitly convertible to an enum. You will have to read in an int and then cast it yourself. Example,

int resInt;
scanf("%d", &resInt);
res = static_cast<ResMode>(resInt);//Note that this does not do bound checking.
like image 28
Pradhan Avatar answered Jan 30 '26 17:01

Pradhan



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!