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 th
This is a typical symptom of the while (!infile.fail())
anti-pattern.
I'd define a struct and overload operator>>
for that type:
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;
}
With those defined, reading the data borders on trivial:
std::ifstream inputFile("fileNameHere");
std::vector<New_Item> items { std::istream_iterator<Item>(inputFile),
std::istream_iterator<Item>() };
[I changed it from list
to vector
, because, well, you really don't want list
. You can change it back, but probably shouldn't.]
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);
}
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.