Mohammad QLFX
Mohammad QLFX

Reputation: 11

How can i input string value and output a value of variable int/float/double

I try to make code that calculate the average

string uD;
int SAMI=24;
cin>>uD;
cout<<uD;

if i input string like "SAMI" the output will be "SAMI"

How can I output the integer of variable value SAMI like this:
input:

SAMI

output:

24

Upvotes: 0

Views: 48

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122595

If you want a mapping between names and numbers you need to implement it yourself. Names of variables do not exist once you compiled the code (only in debug builds for use of a debugger but not as strings accessible in the program).

if (uD == "SAMI") std::cout << SAMI;

If you have more "named numbers" consider to use a std::unordered_map (I used double values here, because you ask for int/float/double but in the example there is only an int, so I wasn't sure):

std::unordered_map<std::string,double> mymap{
       { "SAMI", SAMI },
       { "Foo", 42 }
};
auto it = mymap.find(uD);
if (it == mymap.end()) {
    std::cout << "wrong name";
} else {
    std::cout << it->second;
}

Upvotes: 3

Related Questions