C++ 如何使用字符串生成if语句?在c++;
我一直在做一个模仿收银机软件的项目。 我列出了一个你可以购买的产品清单,并为你输入产品名称。现在我的问题出现在这里,我想以某种方式将产品名称与价格联系起来。 我该怎么做C++ 如何使用字符串生成if语句?在c++;,c++,C++,我一直在做一个模仿收银机软件的项目。 我列出了一个你可以购买的产品清单,并为你输入产品名称。现在我的问题出现在这里,我想以某种方式将产品名称与价格联系起来。 我该怎么做 //i wanted this in my code int appleprice if(product == apple(for example)) { cout << appleprice; } //how my code is #include <iostream> #include
//i wanted this in my code
int appleprice
if(product == apple(for example))
{
cout << appleprice;
}
//how my code is
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Pproduct;
int Pquantity;
double Wallet = rand() %38217;
int Apple = 0.99;
cout <<"\n\nWelcome to the A&L\n";
cout <<"you have " << Wallet << "eur on your account\n";
cout <<"Here is the list of products\n\n\n\n";
cout <<"****************************************\n";
cout <<"* LIST OF PRODUCTS *\n";
cout <<"* *\n";
cout <<"* *\n";
cout <<"* Apple---------------------------0.99 *\n";
cout <<"* Bread---------------------------0.66 *\n";
cout <<"* Cake----------------------------1.80 *\n";
cout <<"* Cheese--------------------------1.90 *\n";
cout <<"* Chicken-------------------------6.30 *\n";
cout <<"* Salad---------------------------1.90 *\n";
cout <<"* Salmon--------------------------4.20 *\n";
cout <<"* Port Wine-----------------------5.90 *\n";
cout <<"* Beer----------------------------2.00 *\n";
cout <<"* Egg-----------------------------0.50 *\n";
cout <<"* Chips---------------------------1.00 *\n";
cout <<"* *\n";
cout <<"* *\n";
cout <<"****************************************\n";
cout <<"\n\n to select a product please insert the name, and quantity\n";
cout <<"When done, press the E key for payment\n";
cin >> Pproduct;
cin >> Pquantity;
cout << Pproduct <<" was added to your cart";
return 0;
}
//我想在我的代码中包含这个
int应用程序价格
如果(产品==苹果(例如))
{
cout您可以将产品放在一个数组中,将价格放在一个带有相应下标的单独数组中。这样,您可以通过使用相同下标来显示产品及其价格,从而在两个数组之间创建连接。您可以使用关联容器,例如或代替if
语句:
#include <map>
#include <string>
#include <iostream>
std::map<std::string, double> price_map = {{"apple", 0.99},
{"bread", 0.66},
{"cake",1.80}};
void foo(const std::string& product)
{
auto iter = price_map.find(product);
if (iter != price_map.end())
std::cout << "The price for " << iter->first << " is " << iter->second << "\n";
else
std::cout << "The product named "\" << product << "\" was not found\n";
}
int main()
{
foo("apple");
foo("bread");
foo("beer");
}
你可能会使用地图或类似的结构。但以目前的形式来说,这是一个太宽泛的问题。听起来你需要一本关于数据结构以及如何在类中表达你的想法的好书、好课或教程(虽然地图
可能是一个开始,但当您需要跟踪需要出售的数量或已经售出的数量时会发生什么情况)当你有其他选择时,使用并行数组不是一个好主意。如果你不小心,它们很容易出错。当人们不太了解数据结构和数据建模方法时(即,他们只了解数组,而不了解类
或映射
,等等),就会使用并行数组。
The price for apple is 0.99
The price for bread is 0.66
The product named "beer" was not found