有人可以帮助我如何在文件处理c ++中多行?我想阅读从search up to 3 next line
开始的行。
ifstream fileInput;
fileInput.open("D:\\devc++\\program\\sample.txt");
string lines, search;
cout << "Enter employee number to search for: ";
cin >> search;
while(!fileInput.eof()){
getline(fileInput,lines);
if(lines.find(search)!=string::npos)
{
cout << "Found " << lines << endl;
cout<<"\n";
}
}
答案 0 :(得分:1)
如下所示更改您的代码,如果您想在下面的代码行search
下面找到该代码行,那么您想要打印下面的3行代码。
ifstream fileInput;
fileInput.open("D:\\devc++\\program\\sample.txt");
string lines, search;
cout << "Enter employee number to search for: ";
cin >> search;
int found = 0;
while(!fileInput.eof()){
getline(fileInput,lines);
if(found > 0 || lines.find(search)!=string::npos)
{
cout << "Found " << lines << endl;
cout<<"\n";
found ++;
if(found > 3)
found = 0;
}
}
更好地纠正您的代码,如下所示
//while(!fileInput.eof()){
while(getline(fileInput,lines)){
//getline(fileInput,lines);
if(found > 0 || lines.find(search)!=string::npos)
{
cout << "Found " << lines << endl;
cout<<"\n";
found ++;
if(found > 3)
found = 0;
}