2013-10-08 103 views
2

我使用下面的代码读取文件,搜索给定的字符串,并显示该行。但我想阅读immediate next line到我在文件的字符串搜索中找到的内容。我可以增加行号以获得下一行,但是我需要在文件上再次使用getline吗?从.txt文件一次读取两行 - C++ getline/streams?

这里是我的代码:

#include <string> 
#include <iostream> 
#include <fstream> 

    int main() 
    { 
     std::ifstream file("data.txt") ; 
     std::string search_str = "Man" ; 
     std::string line ; 
     int line_number = 0 ; 
     while(std::getline(file, line)) 
     { 
      ++line_number ; 

      if(line.find(search_str) != std::string::npos) 
      { 
       std::cout << "line " << line_number << ": " << line << '\n' ; 
       std::cout << ++line_number; // read the next line too 
      } 

     } 

     return (0); 
    } 

这里是我的文件的内容:

Stu 
Phil and Doug 
Jason 
Bourne or X 
Stephen 
Hawlkings or Jonathan 
Major 
League or Justice 
Man 
Super or Bat 
+0

我不能确定ü想要什么。你想仅在匹配后显示下一行还是匹配行和下一行? – goji

+0

是特洛伊,匹配线和紧跟其后的行... – highlander141

回答

1

是的,你将需要getline函数读取下一行。

while(file && std::getline(file, line)) 
    { 
     ++line_number ; 

     if(line.find(search_str) != std::string::npos) 
     { 
      std::cout << "line " << line_number << ": " << line << '\n' ; 
      std::cout << ++line_number; // read the next line too 
      std::getline(file, line); // then do whatever you want. 

     } 

    } 

请注意的file的条款时,这是非常重要的用途。 istream对象可以被评估为boolean,这相当于file.good()。要检查状态的原因是第二getline()功能可以达到这个目的的文件,并抛出一个异常。您也可以在第二getline调用后添加的校验和break如果!file.good()补充。

std::getline(file, line); // then do whatever you want. 
if(line.good()){ 
    // line is read stored correctly and you can use it 
} 
else{ 
    // you are at end of the file and line is not read 
    break; 
} 

那么检查将不是必要的。

+0

我不知道,如果你不小心重复使用相同的变量名,但'file'因为输入流和布尔标志或者不正确(如姓名冲突)或不必要的(因为getline返回'ostream&')。他可以摆脱简单的设置,当他发现结果的布尔标志,并在接下来的循环(读取行之后),测试它,并打破循环。 –

1

您需要创建一个新的bool标志变量,您在找到匹配项时设置该标志变量,然后在找到匹配项后再次循环,以便可以获取下一行。测试该标志以确定您是否在前一个循环中找到了匹配项。

+1

在得到一些指导后,你应该尝试为自己找出这些东西。你会不会以其他方式学到什么:看到这里反正:http://coliru.stacked-crooked.com/a/d4b080eec491313a – goji

+0

嘿特洛伊,我使用由扎克作为所述下面的代码,这是正确的或任何内存泄漏或有什么错误吗? - 请在这里查看:http://ideone.com/V2E4g3 – highlander141

2

你并不需要另一个std::getline电话,但你需要一个标志,以避免它:

#include <string> 
#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::ifstream file("data.txt") ; 
    std::string search_str = "Man" ; 
    std::string line ; 
    int line_number = 0 ; 
    bool test = false; 
    while(std::getline(file, line)) 
    { 
     ++line_number; 
     if (test) 
     { 
      std::cout << "line " << line_number << ": " << line << '\n' ; 
      break; 
     } 

     if(line.find(search_str) != std::string::npos) 
     { 
      std::cout << "line " << line_number << ": " << line << '\n' ; 
      test = true; 
     } 

    } 

    return (0); 
}