0

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
WhozCraig
  • 59,130
  • 9
  • 69
  • 128
Abdullah Shahriar
  • 185
  • 1
  • 2
  • 12
  • 2
    Well, after you found your line, you have a for loop that prints the same variable, over and over again. A computer will always do exactly what you tell it to do, instead of what you want it to do, unfortunately. – Sam Varshavchik Sep 12 '16 at 15:38
  • 1
    [FYI] Do not use `while (file.good())`. It is just like `while (file.eof())`: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver Sep 12 '16 at 15:39
  • what should I use instead of **while (file.good())** ? – Abdullah Shahriar Sep 12 '16 at 15:46

2 Answers2

1

Well you are not reading the following two lines with getline if you found your occurence. Basically, you are missing the getline in your for

Ceros
  • 455
  • 3
  • 12
1

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;
                 }
Aganju
  • 5,994
  • 1
  • 9
  • 22