2013-10-08 100 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); 
}