vendredi 4 octobre 2019

find lines (from a file) that contain a specified word

I cannot figure out how to list out the lines that contain a specified word. I am provided a .txt file that contains lines of text.

So far I have come this far, but my code is outputting the amount of lines there are. Currently this is the solution that made sense in my head:

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


void searchFile(istream& file, string& word) {

   string line;
   int lineCount = 0;

   while(getline(file, line)) {
     lineCount++;
     if (line.find(word)) {
       cout << lineCount;
     }
  }
}

int main() {
  ifstream infile("words.txt");
  string word = "test";
  searchFile(infile, word);
} 

However, this code simply doesn't get the results I expect. The output should just simply state which lines have the specified word on them.

Aucun commentaire:

Enregistrer un commentaire