There's a small problem with SamuelAdams' code. The
inputfile
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,
inputfile.good()
will still return true. It will not be false until after the next
getline
. To solve this, change
while ( inputfile.good())
to
while (true)
and test for
inputfile.good()
after the
getline(inputFile, lastName[i], ',');
line, and
break
if the stream is not good.
Another better possibility is to put the first
getline
inside the
while
condition. When used like this,
getline
acts like a boolean and returns the state of the file stream after the read, which is what you want.
1 2 3 4
|
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
. I'm assuming you are using a
vector<string>
or a
string[]
to store the data that has been resized ahead of time. If you use
vector<string>
, then you can use the
push_back()
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.
1 2 3 4 5 6 7 8 9 10 11
|
string data;
while(getline(inputFile, data, ','))
{
lastName.push_back(data);
getline(inputFile, data);
firstName.push_back(data);
// etc.
}
|
In each
getline()
call,
data
is overwritten with the new text from the file.