C ++ searches for a text file for a particular line and returns the number of the line that this line is in.

Is there a specific function in C ++ that can return the line number of the particular line 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:

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

This will return the line number followed by the search string.

+5
source share
2 answers

Just use the counter variable to keep track of the current line number. Every time you call getline, you ... read the 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())

it should be

while(getline(fileInput, line))

eof , , . std::getline (, ), bool, , , .

eof, , , , , bad, - ..

+10

. [ , .] ,

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

(, , ). 0 find ,

+4

All Articles