[英]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
?我可以这样当我输入
apple
作为输入时, item
实际上从名为apple
的变量中获取值5
吗? With this code, I get 0
as the result.使用此代码,我得到
0
作为结果。
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.您可以使用
string
键和int
值创建map
,将必要的数据存储在该映射中(而不是单独的变量),并使用从std::cin
读取的值作为索引。
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;
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.
对于用户来说,这可能是一个更健壮的界面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.