I'm trying to make a C++ program which finds a specific line in a text file and then reads the next 3 line of that file. But the program is ending up showing the same line three times.What could be a possible fix for this? Here is my code-
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("file.txt");
string line;
int iffound=0;
string inp;
cin>>inp;
cout << "You have searched for " << inp << endl;
while (file.good())
{
getline(file,line);
if(line==inp){
iffound=1;
cout << "Contact Found!" << endl;
for(int i=0;i<=2;i++){
cout << line;
}
break;
}
}
file.close();
if(iffound!=1){
cout << "Contact Not Found" << endl;
}
return 0;
}
Here is my text file (file.txt)
123456
User1
Available
Active
789456
User2
Not Available
Active