我使用下面的代码读取文件,搜索给定的字符串,并显示该行。但我想阅读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