0

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.

  • Similar question about end-of-line detection already answered [here][1] [1]: http://stackoverflow.com/questions/18324189/detect-new-line-c-fstream – TheMP May 20 '14 at 08:17
  • 2
    using a `while(!infile.eof())` loop is a bad idea – M.M May 20 '14 at 08:24
  • Can you clarify "read a line then keep looping until the end of that line". The only way to read a line is to get to the end of the line. Did you mean that you want to read a line, and then break up the line you read into parts? – M.M May 20 '14 at 08:25
  • yes thats correct Matt, sorry for the confusion. – user3553666 May 20 '14 at 08:28

3 Answers3

1

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...
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
1

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.

MultiVAC
  • 354
  • 1
  • 10
1

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.

utnapistim
  • 26,809
  • 3
  • 46
  • 82