Search code examples
c++stringevaluate

Get value from integer whose name is on a string


int a = 1;
int b = 2;
int c = 3;
std::string TakeFrom = "a";

How can I get the value from TakeFrom, in this case, a, and read the integer named like that? For example, in the code above I would have to read a's value because 'a' is what TakeFrom contains, so I'd get "1", but if TakeFrom contained "b", I'd get b's value (2).


Solution

  • If a, b, and c must stay the local ints, the only way you do it is the boring one, i.e. like this:

    int val;
    if (TakeFrom == "a") {
        val = a;
    } else if (TakeFrom == "b") {
        val = b;
    } else if (TakeFrom == "c") {
        val = c;
    } else {
        // It's an error
    }
    

    If you are open to some changes, there are several things that you could do:

    • If you are willing to "encode" the TakeFrom, making it an integer instead of a string (say, 0 means a, 1 means b, and 2 means c), you could place a, b, and c into an array, and use the integer TakeFrom as an index.
    • If you are willing to allow only single-character variables, you could replace the sequence of conditionals with a single switch.
    • If you are open to using standard collections, replace the individual variables with a map of string to integer.