简体   繁体   English

使用字符串引用C ++中的变量

[英]Using a string to reference a variable in C++

Is it even possible to use a string to reference a variable in c++? 甚至可以在C ++中使用字符串来引用变量吗? Note that this is a wrapper around ac project. 请注意,这是ac项目的包装。

I have an incoming message that looks like with data populated in all 3 variables: 我收到一条传入的消息,看起来像所有3个变量中填充的数据:

struct {
  char[20] var_a;
  char[20] var_b;
  char[20] var_c;
} data_type;

Additionally, I have another incoming message that can either be a string of "var_a", "var_b", or "var_c" 另外,我还有另一个传入消息,可以是字符串“ var_a”,“ var_b”或“ var_c”

Is there anyway I can extract the data based on my incoming message. 无论如何,我可以根据传入的消息提取数据。

For example 例如

char new[20] = str2var("var_a")

Where str2var is just there to represent what I am trying to do. 哪里有str2var代表我要做什么。 The size of the message and the data are already defined, I just need the ability to select which data to pull out based on another function. 消息的大小和数据已经定义,我只需要能够根据另一个功能选择要提取的数据。

Any other ideas to accomplish this goal are welcomed. 欢迎任何其他实现此目标的想法。

From what you described, you should be able to index the last character, and just use a case statement. 根据您的描述,您应该能够索引最后一个字符,并且只需使用case语句即可。

char[20] m2;  // second message

switch (m2[4]) {

  case 'a':
    // use var_a
    break;

  case 'b':
    // use var_b
    break;

  case 'c':
    // use var_c
    break;

  default:
    // error
    break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM