How do I search a string from a file and return the line location using functions in C++?

39 Views Asked by At

I am trying to make a program that lets me search for groups of words in a file and then it would return the line locations where they are found. I made it work for a little bit but for some reason, the value of int FileLine (line location) keeps on stacking up whenever a new word search is introduced.

include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

string S1, S2, S, Line;
int FileLine = 0;

int CountInFile(string S) {
    ifstream in("DataFile.txt");
    while (getline(in, Line)) {
        FileLine++;
        if (Line.find(S, 0) != string::npos) {
            cout << "Found " << S << " at line " << FileLine << "\n";
        }
    }
    return 0;
    in.close();
}


int main()
{
    // Words to search
    CountInFile("Computer Science");
    CountInFile("Programming");
    CountInFile("C++");
    CountInFile("COSC");
    CountInFile("computer");

This is the output:

Output image

Is there a way that I can stop the FileLine value from stacking?

0

There are 0 best solutions below