我使用下面的代碼讀取文件,搜索給定的字符串,並顯示該行。但我想閱讀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
我不能確定ü想要什麼。你想僅在匹配後顯示下一行還是匹配行和下一行? – goji
是特洛伊,匹配線和緊跟其後的行... – highlander141