2

I have a structure

struct MyStruct
{
    int intValue1;
    float floatValue2;
    std::string stringValue3;
} Structure;

Now based on the value input of two strings, I want to assign values to the data elements of the structure:

std::string varName = "intValue1";
std::string varValue = "5";

So based on the two strings the "intValue1" should get a value of 5

Structure.intValue1 = (int)varValue;

Is it possible to write a function which would automatically assign values to the structure based on the input strings, e.g.:

 void SetData( std::string varName , std::string varValue );
kmoser
  • 8,780
  • 3
  • 24
  • 40
Summit
  • 2,112
  • 2
  • 12
  • 36
  • 1
    `Structure.intValue1 = std::stoi(varValue);` will probably work better. – Eljay May 28 '20 at 02:28
  • 1
    This *looks* like you want to convert a string to a variable name. That's not currently possible in c++. – cigien May 28 '20 at 02:29

1 Answers1

3

Yes, it is possible, using stringizing operator . Here is a minimalistic example:

#include <string>
#include <iostream>
#define NAME_OF( v ) #v

struct MyStruct
{
    int intValue1;
    float floatValue2;
    std::string stringValue3;
} Structure;


int main()
{
  MyStruct A;

  std::string varName = "intValue1";
  std::string varValue = "5";

  auto var_name = NAME_OF(A.intValue1);

  if (varName.compare(var_name) != 0) {
    A.intValue1 = std::stoi(varValue);
  }
  std::cout << A.intValue1 << " " << varValue << std::endl;
}

Hope this helps!

Aramakus
  • 1,910
  • 2
  • 11
  • 22