且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++在文本文件中搜索特定字符串并返回该字符串所在位置的行号

更新时间:2022-12-30 13:18:39

只需使用计数器变量来跟踪当前行号.每次调用 getline 时,您都会...读一行...因此在此之后增加变量即可.

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;
    }
}

还...

while(!fileInput.eof())

应该是

while(getline(fileInput,line))

如果在读取 eof 时发生错误,则不会设置,因此存在无限循环. std :: getline 返回一个流(您通过它的流),该流可以隐式转换为 bool ,它告诉您是否可以继续阅读,不仅限于您位于文件末尾.

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.

如果设置了 eof ,您仍将退出循环,但是如果设置了 bad ,例如有人在阅读时删除文件,您也将退出循环等等

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.