comparing variable name and string value

Hi all, I checked out a bit of posts similar to this one but none were quite what I am trying to do. I think the answer is that I cannot do it this way but if I do not ask I will not know for certain.

I am trying to compare a strings value with a variables name. My goal is just to prevent using a massive if..else statement every time. So for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main (){

string stat;
int strength = 18;
int constitution = 18;
int dexterity = 18;

cout << "Which stat do you want to alter: Strength, Constitution or Dexterity?";
cin >> stat;

/*what I want to do - my guess is that if the variable names do not exist then there is nothing to compare to */

stat value = stat value + 2;

//what i do not want to do because duh

if (stat == "strength")
{ strength = strength + 2;}
else if (stat == "constitution")
{ constitution = constitution + 2;}
else {dexterity = dexterity + 2;}

return 0;
}
Last edited on
closed account (48T7M4Gy)
line 19 missing "
Last edited on
If the variables are all of the same type, use a look up table which holds wrapped references.
It would be easier for the user to enter a choice if the key is an integer rather than a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <map>
#include <functional>

int main()
{
    int strength = 18; // 1
    int constitution = 18; // 2
    int dexterity = 18; // 3
    
    //  http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
    const std::map< int, std::reference_wrapper<int> > variables =
                            { { 1, strength }, { 2, constitution }, { 3, dexterity } } ;

    std::cout << "Which stat do you want to alter: 1. Strength, 2. Constitution or 3. Dexterity (1/2/3)?";
    int choice ;
    std::cin >> choice ;

    const auto iter = variables.find(choice) ;
    if( iter != variables.end() ) iter->second += 2 ;
    else std::cerr << "invalid choice\n" ;
}
Kemort: Thank you, typed on the fly and did not catch it!

JLBorges, thank you for that information. I do not understand any of it yet so will keep reading :)
closed account (48T7M4Gy)
jkjacks

You could also use a switch statement with cases 1, 2 & 3 etc ...
Topic archived. No new replies allowed.