如何使用fstream读取文件的特定行

How to read specific line of file using fstream?

本文关键字:文件 何使用 fstream 读取      更新时间:2023-10-16

我是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;
     }
    }
}