C++ 将文件逐行输入到结构中
我在将文件的行放入结构时遇到问题。它一次又一次地输入同一行。下面是函数C++ 将文件逐行输入到结构中,c++,C++,我在将文件的行放入结构时遇到问题。它一次又一次地输入同一行。下面是函数 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++
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
bool readInventory(字符串文件名)
{
int-answer=false;
ifstreamopenfile;
openfile.open(文件名);
如果(!openfile.eof())
{
产品*P产品;
p产品=新产品[21];
对于(int i=0;i>p产品[i].PLU;
openfile>>pProducts[i]。名称;
openfile>>pProducts[i].opption;
openfile>>pProducts[i]。价格;
openfile>>P产品[i]。金额;
}
对于(int i=0;i您正在一次又一次地打印相同的产品。在第二个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;
}
for(int i=0;i