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?

6
  • First, you need to read all the lines in a loop. Commented Apr 14, 2020 at 17:04
  • Does this answer your question? Read File line by line to variable and loop Commented Apr 14, 2020 at 17:11
  • Right idea, but the selected answer in that dupe doesn't really read line by line. Commented Apr 14, 2020 at 17:14
  • @cigien Can you please explain it explicitly through a code? Commented Apr 14, 2020 at 17:19
  • @LonesomeParadise I want to display just one particular line. The suggested solution explains how to print every line. Commented Apr 14, 2020 at 17:22

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

-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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.