10

Is there a particular function in c++ that can return the line number of a particular string i want to find?

ifstream fileInput;
int offset;
string line;
char* search = "a"; // test variable to search in file
// open file to search
fileInput.open(cfilename.c_str());
if(fileInput.is_open()) {
    while(!fileInput.eof()) {
        getline(fileInput, line);
        if ((offset = line.find(search, 0)) != string::npos) {
            cout << "found: " << search << endl;
        }
    }
    fileInput.close();
}
else cout << "Unable to open file.";

I want to add some codes at:

    cout << "found: " << search << endl;

That will return the line number followed by the string that was searched.

John Marston
  • 11,549
  • 7
  • 23
  • 18

2 Answers2

18

Just use a counter variable to keep track of the current line number. Each time you call getline you... read a line... so just increment the variable after that.

unsigned int curLine = 0;
while(getline(fileInput, line)) { // I changed this, see below
    curLine++;
    if (line.find(search, 0) != string::npos) {
        cout << "found: " << search << "line: " << curLine << endl;
    }
}

Also...

while(!fileInput.eof())

should be

while(getline(fileInput, line))

If an error occurs while reading eof will not be set, so you have an infinite loop. std::getline returns a stream (the stream you passed it) which can be implicitly converted to a bool, which tells you if you can continue to read, not only if you are at the end of the file.

If eof is set you will still exit the loop, but you will also exit if, for example, bad is set, someone deletes the file while you are reading it, etc.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • oh my i cant believe i didnt think of that simple counter method. i was thinking that there is a special function to call.. thanks i solved it. – John Marston Sep 17 '12 at 16:55
  • @JohnMarston: No problem, make sure you change that loop condition though. As it stands you cannot handle an error condition. – Ed S. Sep 17 '12 at 17:10
6

A modified version of the accepted answer. [A comment on the answer as a suggestion would have been preferable but I can't comment yet.] The following code is untested but it should work

for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
    if (line.find(search) != string::npos) {
        cout << "found: " << search << "line: " << curLine << endl;
    }
}

for loop makes it slightly smaller (but perhaps harder to read). And 0 in find should be unnecessary because find by default searches the whole string

studiou
  • 301
  • 3
  • 6