将文件逐行输入到结构中
inputting a file line by line into a structure
我在将文件的行放入结构中时遇到问题。它一次又一次地输入同一行。这是的功能
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
(
相关文章:
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 重载运算符>>() 表示未知的输入长度/结构
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 我应该如何在C++中使用结构体解决输入失败的问题?
- c ++数据输入并读回列表中的结构结构中的数组
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 我觉得我放入结构中的输入代码可以压缩,关于如何在保持代码简短的同时保持数据个性化的任何建议?
- 从输入中删除重复项,而不使用任何数据结构
- 如何获取结构C++的输入
- 当使用 std::CIN 输入结构时,它会出错
- 输入日,月,年并存储在单独的结构中
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 为什么我不能从结构将数据输入到字符数组中?
- 遍历我的数据结构,并向其中输入随机值
- 按字母顺序打印结构输入C
- C++ 结构输入:_getch()
- 设置类成员函数的结构输入的默认值
- 机器学习数据结构输入的最佳实践