0

Can someone help me how can I multiple lines in file handling c++ ? I want to read the lines that starts from the 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";
        }

 }
Aftab H.
  • 1,493
  • 4
  • 12
  • 25
Keii
  • 29
  • 1
  • 7
  • 1
    At the first glance, `while(!fileInput.eof())` looks bad. [c++ - Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – MikeCAT Mar 05 '18 at 15:53
  • 1
    What's the problem? Where you have `cout << "Found " << lines << endl;` you just put `getline(fileInput,line_1); getline(fileInput,line_2); getline(fileInput,line_3);`, checking for errors, of course, and then process `line_1`, `line_2`, `line_3` - or am I missing something? – Mawg says reinstate Monica Mar 05 '18 at 15:55
  • @Mawg what i'm trying to create is a record and i want it to show all the record of the employee . so i only want to let the user input a employee no. and it will show the records of the employee . – Keii Mar 05 '18 at 15:59
  • See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Thomas Matthews Mar 05 '18 at 17:05

1 Answers1

1

Change your code like below, As you want to print next 3 lines once you find the line have sub string search below code will do that for you.

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;
        }

 }

Better correct your code like below as

 //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;
    }
Abhijit Pritam Dutta
  • 5,010
  • 2
  • 6
  • 16
  • See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). You should present a better solution that the OP's. – Thomas Matthews Mar 05 '18 at 17:05
  • @ThomasMatthews, Thanks for your advice. I have corrected my answer. – Abhijit Pritam Dutta Mar 05 '18 at 17:20