我在将文件行放入结构时遇到问题。它一遍又一遍地输入相同的线。这是函数
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
任何帮助将不胜感激。
答案 0 :(得分:3)
您反复打印相同的产品。在第二个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
)