0

I want my program to look for a student's name in a text file and then display that particular line.

I'm just getting the first line of the text file as output and not the line I'm looking for.

void OTHERS::search_acc()
{
  string srch;
  string line;

  fstream Myfile;
  Myfile.open("STUDENTS", ios::in|ios::out);
  cout << "\nEnter Student Name: ";
  cin.ignore();
  getline(cin, srch);

  if(Myfile.is_open())                                //The problem is in this if block
  {
      getline(Myfile, line);
      line.find(srch, 0);
      cout << "\nSearch result is as follows: \n" << line << endl;
  }
  else
  {
    cout << "\nSearch Failed...  Student not found!" << endl;
    system("PAUSE");
  }  
}

Also, is it possible to return the location of the string I'm looking for in the text file?

James Z
  • 11,838
  • 10
  • 25
  • 41
DC007744
  • 78
  • 6

2 Answers2

1

You need to read all the lines in a loop, and search in each one of them, e.g.

if(Myfile.is_open())
{
  while(getline(Myfile, line))                 // read all the lines
    if (line.find(srch) != std::string::npos)  // search each line
      cout << "\nFound on this line: \n" << line << endl;
}
cigien
  • 50,328
  • 7
  • 37
  • 78
-1
int line=0;
while(!Myfile.eof()){
    getline(Myfile, line);
    line.find(srch, 0);
    ++line;
}
//this line will tell you the line number
cout << "\nSearch result is as follows: \n" << line << endl;

you are reading one line read the whole file

Umar Farooq
  • 377
  • 1
  • 9
  • Recommended reading: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Apr 14 '20 at 17:15