0

Say I have the following struct:

struct movie {
    char movie_name[32];
    int rating;
    int release_year;
    char location;
}

Normally, I would access the rating by saying "movie.rating".

For this project, I have to take input from a text file. I will read a variable such as "movie_name" or "rating" or "release_year" from the file, and given that variable, I have to access the corresponding element of the struct.

Ex: if the input file reads "movie_name", then I want to access movie.movie_name. How do I do this without making 4 if statements? Is there another way?

if(input == "movie_name")
   movie.movie_name = ... 
else if(input == "rating")
   movie.rating = ... 

The real struct I'm working with has 20+ members, so I am trying to find a more efficient way to write this code.

Thanks in advance!

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
EcoRI
  • 3
  • 2

2 Answers2

0

In C/C++ it is not possible to access variable using a string; so there is no way to do this using the struct you provide. A map might be an alternative:

map<string, int>

but then each variable will map on the same type of variable (int in this case)... You should look to the related questions: How to use a string as a variable name in C++? and Convert string to variable name or variable type

Community
  • 1
  • 1
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
0

What you are looking for is called reflection. unfortunately, it is not supported in C++. One solution to your problem which is not an optimal one of course is to implement your struct as map of pair<key,value> as follow:

struct movie {
   std::map<string,ValueType> foo;
}

However, the problem is the ValueType. If boost is available, Then this could be a better solution:

struct movie {
   std::map<string,boost::variant<typeX, typeY>> foo;
}
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160