搜索嵌套类对象的数组?

时间:2015-03-07 18:45:38

标签: c++ class nested

我有一个食品室。 Pantry有一个架子类/嵌套在食品室内。我有一系列货架对象。货架类有一个cookie Num和juice num变量。

我从文件中填充了货架类对象的数组。到目前为止,我的文件阅读工作正常。我做了一个for循环来查看数组是否正确填充,它是。我可以吹嘘所有的价值观。但是现在我想制作一个搜索功能,这样我就可以找到饼干和果汁的库存量。

E.G。 “输入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的信息,一个有juice num的信息。

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

因此,在库存[0],cookie num的值为10.0 juice num的值是22.0。

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

预期:应选择Inventory [0],因为库存[0]的类对象的Cookie数为10.0。

然后输出Inventory [0] cookie num值为10.0且inventory [0] juice num值为22.0。

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

1 个答案:

答案 0 :(得分:1)

问题在于:

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

您实际上正在打印cout的值。删除&lt;&lt;我把它放在**之间,一切都会好的。)

相关问题