gpt4 book ai didi

c++ - 将文件逐行输入到结构中

转载 作者:行者123 更新时间:2023-11-30 02:47:54 24 4
gpt4 key购买 nike

我在将文件行放入结构时遇到问题。它一遍又一遍地输入同一行。这是函数

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 循环中索引产品:

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)

关于c++ - 将文件逐行输入到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com