将文件逐行输入到结构中

inputting a file line by line into a structure

本文关键字:结构 输入 文件 逐行      更新时间:2023-10-16

我在将文件的行放入结构中时遇到问题。它一次又一次地输入同一行。这是的功能

bool readInventory(string filename)
{
int answer= false;
ifstream openfile;
openfile.open(filename);
if(!openfile.eof())
{
    products *pProducts;
    pProducts = new products[21];

    for(int i=0; i<5; i++)
    {
        openfile >> pProducts[i].PLU;
        openfile >> pProducts[i].name;
        openfile >> pProducts[i].opption;
        openfile >> pProducts[i].price;
        openfile >> pProducts[i].amount;
    }
    for(int i=0; i<5; i++)
    {
        cout << pProducts->PLU<<endl;
        cout << pProducts->name<<endl;
        cout << pProducts->opption<<endl;
        cout << pProducts->price<<endl;
        cout << pProducts->amount<<endl;
    }
    answer=true;
    openfile.close();
}
return(answer);

4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2
4020 DELICIOUS_GLDN_LG 1 1.09 84.2
4015 DELICIOUS_RED_REG 1 1.19 75.3
4016 DELICIOUS_RED_LG 1 1.29 45.6

任何帮助都将不胜感激。

您正在一遍又一遍地打印同一个产品。对第二个循环中的产品进行索引,如下所示:

for(int i=0; i<5; i++)
{
    cout << pProducts[i].PLU<<endl;
    cout << pProducts[i].name<<endl;
    cout << pProducts[i].opption<<endl;
    cout << pProducts[i].price<<endl;
    cout << pProducts[i].amount<<endl;
}

另外,不要忘记delete[]您的pProducts指针!您当前内存泄漏。(您真的应该使用std::vector(