从c ++中的txt文件中读取特定行

时间:2012-10-08 08:30:05

标签: c++ file io

所以,我找到了一个我想读的文件的特定行,但是我得到的是不行的:

    string str;
int target = 0;
ifstream record;

record.open("Record.txt");
target = std::count(std::istreambuf_iterator<char>(record), std::istreambuf_iterator<char>(), '\n') - 8;
cout << target << endl;

for(int lineNum = 0; lineNum <= target; lineNum++)
{
    getline(record, str);
    if(lineNum == target)
    {
        cout <<"the id: "<< str << endl;
    }
}

在上面,我使用std :: count来计算文件的行数。我知道我总是想从底部读取第八行,所以我将目标设定为。接下来,我遍历每一行到目标时间,并检查我是否在目标线。如果是这样,那么就行了。

然而,它并没有给我任何东西。对于包含22行的文件,我得到以下输出:

14
the id:

有人可以指出我做错了什么或者给我一些提示吗?谢谢!

1 个答案:

答案 0 :(得分:3)

record调用后,eof()流将为std::count(),但代码从不检查std::getline()的返回值,因此不知道失败:始终检查读取操作的返回值。这意味着永远不会填充str,因此在"thid id: "消息之后不会打印任何内容。

您需要重置流或重新打开它。