fin.ignore()跳过文件中的线

fin.ignore() skipping lines in file?

本文关键字:文件 ignore fin      更新时间:2023-10-16

我正在处理一些代码,这些代码从文件中读取信息并将其存储在结构中。它正在处理我丢弃的所有文件,除一个文件外,其中有很多不同的错误。当文件中存在错误时,它会跳过跟随它的行,我不确定为什么。我的代码如下:

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();
}

这是引起问题的文件。

问题是您不会在失败上消耗newline chracter。

为什么不作为字符串解析整行,然后验证它呢?这样,如果验证失败,您将安全地转到下一行。

#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:受读线读取文件的启发。而且,为什么不在普通C样式数组上使用std::vector?考虑一下!