2

I'm working on some code that reads info from a file and stores it in a structure. It's working on all the files I throw at it with lots of different errors in them except for one. When there is an error in the file it's skipping the line that follows it and I'm not sure why. My code is below:

void readFile(char fileName[], accessRecord file[])
{
   ifstream fin(fileName);
   int i = 0;
   while (fin.good())
   {
     fin >> file[i].fileName >> file[i].userName
         >> file[i].timeStamp;
     i++;

     if (fin.fail())
     {
        fin.clear();
        fin.ignore(256, '\n');
     }
   }
fin.close();
}

This is the File that is causing issues.

Kirby
  • 77
  • 9
  • When trying to read the `timestamp`, you're consuming the newline and attempting to consume "schedule.docx". When you run your ignore, you're ignoring until the end of the "schedule.docx" line... – scohe001 Sep 29 '17 at 23:28
  • 1
    Sorta Duplicate: [Read file line by line](https://stackoverflow.com/questions/7868936/read-file-line-by-line). Use answer 1 option 2 as it eliminates most of the problems you'll run into with clearing and ignoring. Also see if you can use a `std::vector` instead of the array. If you can't, I strongly recommend returning i from the function so that you know how many lines were read and don't have to tempt undefined behaviour by guessing. – user4581301 Sep 29 '17 at 23:40
  • This isn’t the problem, but you don’t need to close the file at the end. The destructor will do that. – Pete Becker Sep 30 '17 at 02:12

1 Answers1

1

The problem is that you don't consume the newline chracter on failure.

Why not parsing the whole line as a string, and then validate it? That way, if validation fails, you will safely move on to the next line.

#include <sstream>
#include <string>

std::string line;
while (std::getline(infile, line))
{
    std::istringstream iss(line);
    if (!(iss >>  file[i].fileName >> file[i].userName >> file[i].timeStamp)) { 
        // Error. go to the next line here
        continue;
    }
    // process your data
}

PS: Inspired by Read file line by line. Moreover, why not using std::vector over a plain C style array? Think about it!

gsamaras
  • 71,951
  • 46
  • 188
  • 305