0

So example.txt contains this;

The
Man
Walked
Into
The
Forest

What I would like is for it to show, what line the word "Walked" is on.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  string word = "Walked";
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      if(line == word) {
             // Walked found on line 3
              } else {
      cout << line << endl;
      }
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  system("pause");
  return 0;
}

So, the output of the code would be "The word walked, is on line 3."

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Tom_Weston
1

Well you can use a counter variable and increment it until you find the word.

//...
int lineCount = 1;
while ( myfile.good() )
    {
      getline (myfile,line);
      if(line == word) {
             cout << "Walked was found on line " << lineCount;
              } else {
      lineCount++;
      cout << line << endl;
      }
    }
//...
Votes + Comments
Very thankful, and useful
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.