首页 > 解决方案 > 如何修改结构内的值(自动售货机的结构)

问题描述

这是咖啡机操作员模式的代码。通过操作员模式操作员应该能够添加新的咖啡类型并在现有咖啡类型中添加更多咖啡粉。但我不知道如何访问结构内的数据修改它们(添加更多的咖啡粉)。

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>

using namespace std;

struct coffee {
  string name;
  int itemprice;
  string country;
  int quantity;

};

float remainder, price2, price;

int main() {

      int coffeetype = 1; 

 vector <coffee> coffee_drink ={

   { "Espresso", 120, "Italy", 20 },
   {"Iced coffee", 150, "France", 20},
   {"Long black", 80, "Austral", 20},
   {"Americano", 100, "America", 20},
   {"Latte", 200, "Italy", 20},
   {"Irishcoffee", 130, "Ireland", 20},
   {"Cappuccino", 180, "Italy", 20}

   };


   //Add new coffee type
      coffee enter_coffee;
         cout << "Enter the detailsof new coffee here!" << endl
              << "Enter the name of new coffee type"<<endl;
         cin >> enter_coffee.name;
         cout << "Enter the price of new coffee type"<<endl;
         cin >> enter_coffee.itemprice;
         cout << "Enter the country of origin" << endl;
         cin >> enter_coffee.country;
         cout << "Enter the quantity" << endl;
         cin >> enter_coffee.quantity;

         coffee_drink.push_back(enter_coffee);

   //Cout coffee names      
            cout << fixed;
        cout << setprecision(2);   
for (int i = 0; i != coffee_drink.size(); ++i){
        cout<< "\n " << i+1 << ") "<<coffee_drink[i].name<<"\t\t"<<coffee_drink[i].itemprice<<"\t\t"<<coffee_drink[i].country<<"\t\t("<<coffee_drink[i].quantity<<") remaining";}


}

通过上面的代码部分,我只能添加一种新的咖啡类型。但我想在现有的咖啡类型中添加更多的咖啡粉

 vector <coffee> coffee_drink ={

   { "Espresso", 120, "Italy", 20 },
   {"Iced coffee", 150, "France", 20},
   {"Long black", 80, "Austral", 20},
   {"Americano", 100, "America", 20},
   {"Latte", 200, "Italy", 20},
   {"Irishcoffee", 130, "Ireland", 20},
   {"Cappuccino", 180, "Italy", 20}

   };

这里默认的咖啡杯数量是 20。但是当人们再见咖啡时它会减少。所以在这里我想在减少时添加更多的咖啡杯。有人可以帮我解决这个问题吗?

标签: struct

解决方案


您可以通过适当的索引直接更改任何咖啡类型。例如。增加expresso的数量:

coffee_drink[0].quantity += 10;//this will add 10 more cups of coffee

您可以类似地更改其他咖啡类型的数量。


推荐阅读