繁体   English   中英

在C ++中从txt文件读取指定行

[英]Reading a specif line from a txt file in c++

因此,我找到了要读取的文件的特定行,但是我无法使用:

    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:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM