0

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 3
    No, in C++ the name of a variable *only exists* while the code is being compiled (except perhaps for some debug-mode hacks designed to help find problems in the code). The program cannot look for the name `apple` because it is not actually stored anywhere that it could be found. Instead, use a data structure that explicitly does that mapping, such as `std::map`. – Karl Knechtel Jun 30 '22 at 06:35
  • Hello, you can also check this post about hashmap in cpp https://stackoverflow.com/questions/3578083/what-is-the-best-way-to-use-a-hashmap-in-c – Débart Rédouane Jun 30 '22 at 06:41

2 Answers2

3

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;
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
MFischer
  • 107
  • 9
0

You can use a map, as shown in the other answer. Another choice would be to show the user a numbered list:

1: apple - $10
2: banana - $15
3: ...

And then ask them to enter a number. Then use the number to access the element in the array of products. This might be a more robust interface for the user.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93