如何为结构的数据元素赋值

How to assign values to the data elements of a structure

本文关键字:数据 元素 赋值 结构      更新时间:2023-10-16

我有一个结构

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

现在基于两个字符串的值输入,我想为结构的数据元素赋值:

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

因此,基于这两个字符串,"intValue1"应获得值 5

Structure.intValue1 = (int)varValue;

是否可以编写一个函数,该函数将根据输入字符串自动为结构赋值,例如:

void SetData( std::string varName , std::string varValue );

是的,这是可能的,使用字符串化运算符。下面是一个简约的例子:

#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;
}

希望这有帮助!