There's a small problem with SamuelAdams' code. The
stream might not enter a bad state until it tries to read from the file after the last line. So, after reading the last line of text,
will still return true. It will not be false until after the next
. To solve this, change
while ( inputfile.good())
and test for
getline(inputFile, lastName[i], ',');
if the stream is not good.
Another better possibility is to put the first
condition. When used like this,
acts like a boolean and returns the state of the file stream after the read, which is what you want.
while(getline(inputFile, lastName[i], ','))
// read rest of line and process data
The other problem with your code is the use of the index
. I'm assuming you are using a
to store the data that has been resized ahead of time. If you use
, then you can use the
method to add another piece of data. In this case, you will want to declare a string to read the data from the file and add to the vector as a separate line.
while(getline(inputFile, data, ','))
is overwritten with the new text from the file.