aarelovich aarelovich - 2 years ago 76
C++ Question

Is there anyway to transform a string to a field in a struct in C++/Qt?

I have an struct like so:

typedef struct {
int field1;
int field2;
} Example;

Example data;

My real structure has about 20 fields. However I would like to assign values to those fields based on parsing a text file. Now, the obvious way of doing this is with a huge switch (or
if-else if
chain) testing on what attribute is being assigned. However this is bothersome and complicated to expand.

Is there any mechanism that would allow to transform a string lifted from a file to a struct field name? So for example if my file had a line
field1 = 23
I would know to assign
to the
without the

Answer Source

You need to write setters:

void setField1(const char *f) ;
void setField2(const char *f) ;

The setters are responsible to decode the string into an int.

Then you need an associative array (hash) that associates the field name to the function:

"field1" -> setField1
"field2" -> setField2

Then you need to grab the function pointer from the associative array and call it with the field as parameter. This is an example:

#include <iostream>

typedef struct {
  int field1;
  int field2;
} Example;

Example data;

void setField1(const char *f) {
  data.field1 = std::stoi(f); 

void setField2(const char *f) {
  data.field2 = std::stoi(f);

void (*tab[])(const char *) = { setField1, setField2 };

int main(void)
  data.field1 = 10 ;
  data.field2 = 20 ;
  tab[0]("43") ;
  tab[1]("12") ;
  std::cout << "fields:" << data.field1 << '|' << data.field2 << std::endl;
  return 0;

Naturally you would need to do more than that to make a correct code. For one, Example should be a class and the setters moved there, then you need to decode the text line to get the indices, or to use an associative array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download