#include <fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream infile("myfile.txt");
string line, input;
cout<<"Input the text u want to find"<<endl;
cin>>input;
infile.open();
while(!infile.eof())
{
while(getline(infile,line))
{
if(line==input)
{
cout<<line<<endl;
}
}
}
}
我只知道如何在一个文本文件中找到一个特定的行并将其输出,但我不知道如何将它上面或下面的行输出。
我的文本文件示例:
玛丽
9am-11am
本尼
10am-12pm
哈里
9am-11am
我的输入示例:
上午9:00-11:00
我想说的是:
玛丽
9am-11am
哈里
9am-11am
例如,你可以这样做
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream infile("myfile.txt");
string line, input, line_above, line_below;
cout<<"Input the text u want to find"<<endl;
cin>>input;
bool k = infile.is_open();
while(!infile.eof())
{
while(getline(infile,line))
{
if(line==input)
{
if (!line_above.empty())
cout<<"Line above: "<<line_above<<endl;
cout<<"Found line at position "<<infile.tellg()<<": "<<line<<endl;
if (getline(infile,line_below))
cout<<"Line below: "<<line_below<<endl;
}
line_above = line;
}
}
}