Abdullah Shahriar Abdullah Shahriar - 2 months ago 8
C++ Question

Trouble reading next line from a file

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

Answer

Your inner loop does no more reading, it just prints it 3 times:

                 for(int i=0;i<=2;i++){
                    cout << line;
                 }

If you want the code to keep reading more lines, you need to put the reading inside that loop too:

                 for(int i=0;i<=2;i++){
                    getline(file,line);
                    cout << line;
                 }
Comments