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

标签 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.";

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

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

这将返回行号后跟被搜索的字符串。

最佳答案

只需使用一个计数器变量来跟踪当前行号。每次调用 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;
    }
}

还有...

while(!fileInput.eof())

应该是

while(getline(fileInput, line))

如果在读取时发生错误,eof 将不会被设置,所以你有一个无限循环。 std::getline 返回一个流(你传递给它的流),它可以被隐式转换为一个 bool,它告诉你是否可以继续阅读,而不仅仅是如果你在文件的末尾。

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

关于C++ 在文本文件中搜索特定字符串并返回该字符串所在的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463750/

相关文章:

c++ - 如何在C++中存储具有字符串和整数串联的变量

javascript - 在异步函数更新 Node.js 模块后,如何从该模块返回值?

c - 带返回终止符的 void 函数

c++ - 如何使用cmake编译C++共享库项目?

c++ - 使用 Xbox 360 Controller 的鼠标模拟

c++ - 从获取请求中读取站点正文

search - 如何将 SEO 添加到我的网站?

python - 在 for 循环中的值之后在字典列表中搜索

java - 使用泛型 Java 对数组/比较器进行二分搜索

python - 从 scipy 的 weave.inline 将 C 数组返回到 python 范围