Search code examples
c++filestructwhile-loopifstream

fin.ignore() skipping lines in file?


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.


Solution

  • 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!