【发布时间】:2013-10-14 21:40:06
【问题描述】:
我正在使用下面的代码来读取文件,搜索给定的字符串并显示该行。但我想将immediate next line 阅读到我在文件的字符串搜索中找到的内容。我可以增加行号以获取下一行,但我需要在文件上再次使用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 ;
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
【问题讨论】:
-
我不确定你想要什么。是只显示匹配后的下一行还是匹配的行和下一行?
-
是的特洛伊,匹配的行和紧接的下一行...
标签: c++ string file stream getline