0

What I mean is, how do I use a char, which I can iterate, to identify a variable? So if:

int cheese = 1337;
string identifier = "cheese";

How do I use this string "identifier" to identify the variable cheese and return its value?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Jack Raiden
  • 23
  • 1
  • 7
  • 2
    it's not possible in c++ – Raindrop7 Dec 11 '16 at 20:42
  • 2
    C++ ulike Java does not have reflection so a program once is fully compiled, linked and loaded, it loses all reference to symbol names. The only thing is had is addresses. – doron Dec 11 '16 at 20:51
  • Also https://stackoverflow.com/questions/2911442/access-variable-value-using-string-representing-variables-name-in-c – Baum mit Augen Dec 11 '16 at 20:54

2 Answers2

7

You don't.

Instead, you lay out your data differently, perhaps using a key-value store?

std::map<std::string, int> myData;
myData["cheese"] = 1337;

// ...

const std::string identifier = "cheese";
std::cout << myData[identifier] << '\n';   // 1337
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Looks like you are looking for map

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<string, int> vars;
    vars.insert(make_pair("cheese", 1337));
    vars.insert(make_pair("geese", 1338));
    if (vars.find("cheese") != vars.end())
        cout << vars.at("cheese");
    return 0;
}
roman
  • 1,061
  • 6
  • 14