搜索嵌套类对象的数组

Searching through array of nested class objects?

本文关键字:数组 对象 嵌套 搜索      更新时间:2023-10-16

我有一个餐具室课程。食品储藏室有一个搁架子类/嵌套在食品储藏室内。我有一排货架上的物品。shelf类有一个cookie Num和juice Num变量。

我从一个文件中填充工具架类对象的数组。到目前为止,我的文件读取工作还不错。我做了一个for循环,看看数组是否正确填充。我可以定制所有的值。然而,现在我想做一个搜索功能,这样我就可以找到饼干和果汁的库存量。

例如"输入cookie金额"用户输入5。程序返回任何有5个cookie的货架的信息。

我的问题是,当我尝试使用搜索函数时,我会从数组中返回垃圾值。

class PantryClass
{
double nums1,nums2,nums3;
public:
    class ShelfClass
    {
        public:
        double CookieNum;
        double JuiceNum;
    };
    void otherFunction2(double, double, int);
    void otherFucntion3(double, double, int, double);
};

填充阵列

int main()
{
PantryClass test;
PantryClass::ShelfClass inventory[50];
ifstream inputs(input file name here (this works fine));
ifstream inputs2(input file name here (this works fine));
for(int i = 0; i < 50; i++)
{
    inputs>> inventory[i].CookieNum;
    inputs2>> inventory[i].JuiceNum;
}
int choice;
cout << "Enter choice" << endl;
cin >> choice;
if (choice == 1)
{
    snackSearch(inventory);
}

}

查找函数

    void snackSearch(PantryClass::ShelfClass inventory[])
{
    cout << "Please enter the cookie amount you'd like to find: " << endl;
            int num1;
            cin >> num1;
        for(int i=0; i < 50; i++)
        {
            if (inventory[i].CookieNum == num1)
            {
                cout << " Cookie num is " << cout <<inventory[i].CookieNum << endl;
                cout << "Juice num is  " << cout <<inventory[i].JuiceNum << endl;
            }
        }
}

更新它以显示我使用的2个文本文件。一个文件有饼干编号的信息,一个有果汁编号的信息。

Cookie num文件值:10.0、15.0、20.0果汁数量:22.0、32.0、16.0

因此,在inventory[0]中,cookie num的值为10.0juice num的值为22.0。

在我的搜索功能中,我搜索10.0。

应为:应选择Inventory[0],因为Inventory[0]处的类对象的Cookie编号为10.0。

然后应输出库存[0]饼干数量值10.0和库存[0]果汁数量值22.0。

实际:选择库存[0],但输出的值是数字/值,如0F81C3E810.00F81C3E822.0

问题就在这里:

cout << " Cookie num is " **<< cout** << inventory[i].CookieNum << endl;
cout << "Juice num is  " **<< cout** <<inventory[i].JuiceNum << endl;

你实际上是在打印cout的价值。删除<lt;如果我把它放在**之间,一切都会好起来的:)