Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use a string read from `std::cin` to look up an existing variable by name?

I’m currently trying to make a sort of a shopping cart. When the program asks for items, i type them in; but it needs to remember the values so it can use them later in the code.

I have this code so far:

#include <iostream>

int main() {
    int item{};
    int apple = 5;
    std::cout << "what item do you want to buy?";
    std::cin >> item;
    std::cout << item;
    return 0;
}

Can I make it so that when i type apple as input, item actually gets the value 5, from the variable named apple? With this code, I get 0 as the result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could create a map with string keys and int values, store the necessary data in that map (instead of separate variables), and use the value read from std::cin as an index.

The code looks like:

std::map<std::string, int> fruits;
fruits["apple"] = 5;
std::string choice;
std::cin >> choice;
std::cout << fruits[choice] << std::endl;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading