0

I have a file which has some comma separated rows. I want to get each value in a line (like columns in CSV). I tried to read that with following c++ code:

while (ip.good())
{
    getline(ip, pid, ',');
    getline(ip, npid, ',');
    getline(ip, fid, ',');
    getline(ip, nfid, ',');
    getline(ip, sys, ',');
    getline(ip, gf, '\n');
}

and the file likes following:

2374447,1,2374448,3,16,300
2374447,1,2374449,3,16,300
2374447,1,2374450,3,16,300
2374447,1,2374451,3,16,300
2374447,1,2374452,3,10,300
2374447,1,0,4,20,300
2374447,1,2374453,3,10,300

it reads last line twice or read a empty line as last line! I added one line at the end of the file like: a,a,a,a,a,a. now it read all the lines correctly but returns two extra empty lines. does anyone what's the problem with that?

  • Please, note. If your last line ends with a line-end (`\n`) then `while (ip.good())` takes an extra round. Now, the first `getline(ip, pid, ',')` fails to read as hitting the EOF immediately. Nevertheless, all the other `getline()`s are executed again and are trying to read from a `stream` in fail state. – Scheff's Cat May 23 '21 at 11:51
  • Instead, you should make your `getline()`s itself the condition of `while()` (combined with `&&`s) i.e. `while (getline(ip, pid, ',') && getline(ip, npid, ',') && getline(ip, fid, ',') && getline(ip, nfid, ',') && getline(ip, sys, ',') && getline(ip, gf, '\n'));` (Of course, this can be formatted into multiple lines as you did before.) ;-) – Scheff's Cat May 23 '21 at 11:52
  • Concerning my first comment, I might have been slightly wrong. Correct should be, the first `getline()` will hit EOF immediately, set the EOF flag, return an empty string, and then the 2nd will fail to read leaving the stream in fail state... However, that doesn't change much. (I stumbled into this while recalling [std::getline()](https://en.cppreference.com/w/cpp/string/basic_string/getline).) You are free to prove me right or wrong using your debugger. ;-) – Scheff's Cat May 23 '21 at 11:57

0 Answers0