gpt4 book ai didi

c++ - fin.ignore()跳过文件中的行?

转载 作者:行者123 更新时间:2023-12-01 14:55:13 25 4
gpt4 key购买 nike

我正在研究一些从文件读取信息并将其存储在结构中的代码。它正在处理我扔给它的所有文件,除了一个文件外,其中有许多其他错误。
如果文件中有错误,它将跳过其后的一行,但我不确定为什么。我的代码如下:

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

这是导致问题的 File

最佳答案

问题是您不会在失败时消耗换行符。

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

#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:受 Read file line by line启发。此外,为什么不对纯C样式数组使用 std::vector ?想想看!

关于c++ - fin.ignore()跳过文件中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com