如何使用fstream读取文件的特定行
How to read specific line of file using fstream?
我是c++的新手,遇到了一个问题。我正在学习fstream。我有一个data.txt文件,其中包含类似的内容
[exe1]
1 0 2 9 3 8 4 7 5 6
[exe2]
1 0 2 9 3 8 4 7 5 6:0
[exe3]
23
[exe4]
Micheal
我的问题是如何阅读特定的一行,比如第2行:
1 0 2 9 3 8 4 7 5 6.
提前感谢
如果找到行的唯一方法是在其中搜索一些数据,那么您必须读取每一行,直到找到感兴趣的行:
std::ifstream fs("data.txt");
std::string line;
while(std::getline(fs, line)) {
if ( line.find("[exe2]") != std::string::npos )
{
if ( std::getline(fs, line) ) {
// line found
// line should contain "1 0 2 9 3 8 4 7 5 6:0"
break;
}
}
}
相关文章:
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何在其他文件中使用函数
- 在实现文件中使用头文件的通用 lambda
- 将 getline() 与文件一起使用
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 定义C++新的环境变量并在 bat 文件中使用它
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 在 embarcadero / RAD 工作室中的 .dfm 文件中使用常量
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 如何在 linux 可执行文件中使用静态库
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- CocoaPod - 在头文件中使用 C++ 时出现 Podspec 检查错误
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 如何为文件路径使用变量?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 在带有类型保护的模板文件中使用前向声明
- 无法使包含.hpp文件与其中的2个文件一起使用
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟