获取结构数组中的元素

时间:2014-03-27 16:45:30

标签: c++

该程序从10个箱中选择任意数量相同的箱。当程序选择一个时,它会询问我们是否要添加或删除该特定bin中的部件。如何从结构数组中获取元素      //结构体      struct Inventory     {

   char description[35];
   int num;
 };

 //Function Prototypes.

 void choiceMenu(Inventory[], int);
 void AddParts(Inventory[], int);
 void RemoveParts(Inventory[]);

 int main()
 {
   char election;
   int choice;

   const int Number_Bins = 10;
    Inventory parts[Number_Bins] = {
                                  {"Valve", 10},
                                  {"Bearing", 5},
                                  {"Bushing", 15},
                                  {"Coupling", 21},
                                  {"Flange", 7},
                                  {"Gear", 5},
                                  {"Gear Housing", 5},
                                  {"Vacuum Gripper", 25},
                                  {"Cable", 18},
                                  {"Rod", 12}
                                  };

有没有其他方法可以在不将数组的元素从0添加到9的情况下执行此操作。就像尝试使用累加器一样。如何从数组中获取特定元素。

 void choiceMenu(Inventory bin[], int z)
{


   cout << "                               Inventoy Bins\n";
   cout << "                              = = = = = = = = \n";
   cout << " *Choose the part of your preference.\n";
   cout << " 1. Valve" << bin[0].num << endl;
   cout << " 2. Bearing. Currently Number of Bearing = " << bin[1].num << endl;
   cout << " 3. Bushing. Currently Number of Bushing = " << bin[2].num << endl;
   cout << " 4. Coupling. Currently Number of Coupling = " << bin[3].num << endl;
   cout << " 5. Flange. Currently Number of Flange = " << bin[4].num << endl;
   cout << " 6. Gear. Currently Number of Gear = " << bin[5].num << endl;
   cout << " 7. Gear_Housing" << bin[6].num << endl;
   cout << " 8. Vacuum_Gripper" << bin[7].num << endl;
   cout << " 9. Cable. Currently Number of Cable = " << bin[8].num << endl;
   cout << " 10. Rod. Currently Number of Rod = " << bin[9].num << endl;    
   cout << " 11. Choose 11 to quit the Program" << endl; 

}

1 个答案:

答案 0 :(得分:0)

我在想你是在问如何将一个数组元素传递给一个添加或删除部分的函数。您可以使用引用变量(http://www.cprogramming.com/tutorial/references.html)来完成此操作。

例如,在您的情况下,此函数将删除一个部分:

void RemovePart(Inventory& part)
{
    if (part.num > 0)
        part.num -= 1;
    cout << part.description <<  " now has " << part.num << " parts." << endl;
}

然后你可以用数组元素调用该函数。例如,这将删除一个方位:

RemovePart(bin[1]);