从文件中读取数据并将其存储到矢量中

时间:2015-01-31 01:05:47

标签: c++

我试图从文件中读取项目列表,然后将它们存储到矢量中。问题是我的代码是将最后一项添加到向量中两次,我不确定为什么即使程序已经到达结束它也会继续读取文件。

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

苹果 - 磅-10 2

橘子 - 磅-5 6

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

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();

2 个答案:

答案 0 :(得分:2)

这是while (!infile.fail())反模式的典型症状。

我为该类型定义了一个结构并重载operator>>

struct item { 
    std::string name;
    std::string unit;
    int amount;
    int price;
};

std::istream &std::operator>>(std::istream &is, item &i) { 
    getline(is, i.name, '-');
    getline(is, i.unit, '-');
    is >> i.amount;
    return is >> i.price;
}

通过这些定义,轻松读取数据边界:

std::ifstream inputFile("fileNameHere");

std::vector<New_Item> items { std::istream_iterator<Item>(inputFile),
                              std::istream_iterator<Item>() };

[我将其从list更改为vector,因为,你真的不想要list。你可以改回来,但可能不应该改变。]

答案 1 :(得分:1)

问题是,在您尝试从文件中读取更多数据之前,不会设置“fail”标志。以下是解决此问题的快速方法:

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);
}

如果这是一次学习练习,而你尚未学习>>运算符,那么应该这样做。否则,operator>>方法会更好。

相关问题