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).
If a
, b
, and c
must stay the local int
s, 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:
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.switch
.