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

Joh*_*ton 6 c++ search return

c ++中是否有特定的函数可以返回我想要查找的特定字符串的行号?

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.";
Run Code Online (Sandbox Code Playgroud)

我想在以下位置添加一些代码:

    cout << "found: " << search << endl;
Run Code Online (Sandbox Code Playgroud)

这将返回行号,后跟搜索到的字符串.

Ed *_* S. 13

只需使用计数器变量来跟踪当前行号.每次你打电话给getline你......读一行......所以只需在那之后增加变量.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

也...

while(!fileInput.eof())

应该

while(getline(fileInput, line))

如果在eof未设置读取时发生错误,则会出现无限循环. std::getline返回一个流(你传递它的流),它可以隐式转换为a bool,告诉你是否可以继续读取,不仅是你在文件的末尾.

如果eof设置了,你仍然会退出循环,但是如果bad设置了,有人会在你阅读时删除文件等,你也会退出.


小智 5

已接受答案的修改版本.[作为建议的答案的评论本来是更可取的,但我还不能评论.]以下代码未经测试但它应该工作

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

for循环使它略小(但可能更难阅读).而find中的 0 应该是不必要的,因为默认情况下find会搜索整个字符串