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 items { std::istream_iterator- (inputFile),
std::istream_iterator
- () };
[I changed it from list
to vector
, because, well, you really don't want list
. You can change it back, but probably shouldn't.]