Reputation: 3
I have csv file input where I read in multiple lines which contain multiple fields related to that line. How do I write a loop which reads a line of text from the csv file, then keeps looping until it reaches the end of that line. This while loop would be nested in an !infile.eof while loop. Here is what I has so far but doesn't work exactly.
while (getline(infile, currentline))
{
getline(infile, ID, ',');
getline(infile, Name, ';');
Person p = new Person(ID, Name);
}
A line in the csv file looks like this: 111, james; 222, lynda; 333, luke;
Each line represents a classroom so there would be multiple lines.
Upvotes: 0
Views: 2024
Reputation: 27365
Try this:
while (getline(infile, currentline))
{
std::istringstream line{currentline};
if(getline(line, ID, ',') && getline(line, Name, ';'))
Person p = new Person(ID, Name);
}
This while loop would be nested in an !infile.eof while loop.
As a side note, never iterate while( !infile.eof() )
- this is pretty much guaranteed to be a bug. An input stream has multiple failure conditions (eof, failed read etc).
You should simply cast the stream to a boolean value for checking.
Upvotes: 1
Reputation: 354
Your while loop seems to already extract a line from the "infile" and stores it in "currentline". Inside the loop you should make a stream out of this string, and use the getlines for "ID" and "Name" on the "currentline"-stream. Otherwise, as it is now, I think you lose every other line.
Upvotes: 1
Reputation: 106086
The question's a mess, but I think this is what you want:
while (std::getline(infile, currentline))
{
std::istringstream iss(currentline);
if (getline(iss, ID, ',') &&
getline(iss, Name, ';') &&
...)
{
Person p = new Person(ID, Name);
...
}
else
...bad person ;-P...
}
Upvotes: 1