从文件读取数据并将其存储到向量中 [英] Reading data from a file and storing it into a vector

查看:330
本文介绍了从文件读取数据并将其存储到向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取项目列表,然后将它们存储到向量中。问题是我的代码是将最后一个项目添加到向量两次,我不知道为什么它保持读取文件,即使程序已经到达结束。

I'm trying to read a list of items from from a file and then store them into a vector. The issue is my code is adding the last item to the vector twice and I'm not sure why the it keeps reading the file even though the program has reached the end.

这是文本文件中的内容。显示向量的内容时,橘子行出现两次。

Here's what's in the text file. The "Oranges" line appears twice when I display the contents of the vector.

苹果 - 磅 - 10 2

Apples-pounds-10 2

橘子 - 磅-5 6

Oranges-pounds-5 6

这里是代码
//将列表的内容读入文件

Here's the code //Read the contents of the list to a file

while (!inputFile.fail())
{   

    //Extract the line from the list
    getline(inputFile,item_name,'-');
    getline(inputFile,item_unit,'-');
    inputFile >> item_amount;
    inputFile >> item_price;

    //Create an instance of the item object
    Item New_Item(item_name, item_unit, item_amount,item_price);

    //Push it to the list vector
    list.push_back(New_Item);
}

//Close the file
inputFile.close();


推荐答案

问题是fail设置,直到您尝试从文件读取一些更多的数据。这是一种快速修复此问题的方法:

The problem is that the "fail" flag is not set until you make an attempt at reading some more data from the file. Here is a quick way of fixing this:

for (;;) {
    //Extract the line from the list
    getline(inputFile,item_name,'-');
    getline(inputFile,item_unit,'-');
    inputFile >> item_amount;
    inputFile >> item_price;
    if (inputFile.fail()) break;
    //Create an instance of the item object
    Item New_Item(item_name, item_unit, item_amount,item_price);
    //Push it to the list vector
    list.push_back(New_Item);
}

如果这是一个学习练习, c $ c>>> 运算符,这应该这样做。否则, operator>> 方法更好。

If this is for a learning exercise, and you have not learn the >> operator yet, this should do it. Otherwise, the operator>> approach is better.

这篇关于从文件读取数据并将其存储到向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆