I am working on an assignment where I need to read a CSV file of unknown number of lines into an structured array. Only via C++, not C (they don\'t want us to combine both).
Your file pointer is at the end of the file after the while loop to determine the amount of lines. As I see it you've got the clear and reset the file pointer. This link might help you: http://www.cplusplus.com/forum/beginner/11564/
Your first loop reads the stream. It stops when there is nothing else left to read. At that point the stream goes into failure mode (i.e., std::ios_base::failbit
gets set) and it will refuse to read anything until it gets somehow restored.
You can restore a file to goid state using file. clear()
. That alone won't help, though, as the stream is still at its end. You could seek to the start before reading but I wouldn't do that. Instead, I would read the file in one pass and push_back()
each element to a std::vector<items>
.
Note that the input you have for each items
record probably doesn't quite do what you want it to do: if you really have a CSV file you'll need to read to the separators (e.g. the ,
) and ignore the separator after reading the ID. Also, you should always test the state of the stream after reading. Your loop could e.g. look something like this:
for (items i;
(file >> i.id).ignore(std::numeric_limits<std::streamsize>::max(), ',')
&& std::getline(file, i.name, ',')
&& std::getline(file, i.desc, ',')
&& std::getline(file, i.price, ',')
&& std::getline(file, i.pcs); ) {
is.push_back(i);
}
What is needed exactly somewhat depends on the exact file format.