【问题标题】:C++ searching text file for a particular string and returning the line number where that string is onC++ 在文本文件中搜索特定字符串并返回该字符串所在的行号
【发布时间】:2012-09-09 22:25:33
【问题描述】:

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;

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

【问题讨论】:

    标签: c++ search return


    【解决方案1】:

    只需使用计数器变量来跟踪当前行号。每次你打电话给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、有人在您阅读文件时删除了文件等,您也会退出。

    【讨论】:

    • 哦,我不敢相信我没有想到那种简单的计数器方法。我在想有一个特殊的函数可以调用..谢谢我解决了。
    • @JohnMarston:没问题,但请确保更改该循环条件。就目前而言,您无法处理错误情况。
    【解决方案2】:

    已接受答案的修改版本。 [作为建议对答案发表评论会更好,但我还不能发表评论。] 以下代码未经测试,但应该可以工作

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

    for 循环使它稍微小一些(但可能更难阅读)。 find 中的 0 应该是不必要的,因为 find 默认搜索整个字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多