[Solved] How to adress variable by name stored in another variable (C++)


Variable names disappear as part of the compilation step(s) in C and C++.

Typically, there are two scenarios that solve the type of problem you are describing:

  1. User input corresponds to specific variable name.
  2. You don’t actually want the “name” of the variable, but just need a way to associate different data with different parts of your code.

In the second, simpler case, just use an array, and use the index to the element you want as the way to associate the correct data.

In the first case, you can use a std::map<std::string, structname&>. A std::map acts sort of like an array, but it is indexed by the first type give in the template parameters to std::map – so in this case, you can use std::string as an index.

Something like this:

#include <map>
#include <iostream>
#include <string>

struct StructName
{
    int x;
};

std::map<std::string, StructName *> vars;

StructName a;
StructName b;

void registerVars()
{
    vars["a"] = &a;
    vars["b"] = &b;
}


int main()
{
    std::string v;

    registerVars();

    while(std::cin >> v)
    {
    std::cin.ignore(1000, '\n');

    if (vars.find(v) == vars.end())
    {
        std::cout << "No such variable" << std::endl;
    }
    else
    {
        vars[v]->x++;
        std::cout << "variable " << v << " is " << vars[v]->x << std::endl;
    }
    }
    return 0;
}

1

solved How to adress variable by name stored in another variable (C++)