在 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 来计算文件的行数。 我知道我总是想从底部阅读第 eigth 行,所以我将目标设定为该行。 接下来,我循环遍历每行到目标时间,并检查我是否在目标行。 如果是这样,那就去排队。
但是,它没有给我任何东西。 对于 22 行的文件,我得到以下输出:
14
the id:
有人可以指出我做错了什么或给我一些提示吗? 谢谢!
record
流将在std::count()
调用后eof()
,但代码从不检查std::getline()
的返回值,因此不知道它正在失败:始终检查读取操作的返回值。这意味着永远不会填充str
,因此在"thid id: "
消息之后不会打印任何内容。
您需要重置流或重新打开它。
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中