从该文件中的特定位置查找文件中最后一次出现的字符串

时间:2015-06-11 11:51:34

标签: c++ regex pattern-matching

我想在同一文件中的固定特定位置(分隔符)的初始大小 NODELIST ***pppNode, Node; size_t Row = 5, Col = 5, i; pppNode = malloc( sizeof(NODELIST **) * Row ); for(i = 0; i < Row; i++) pppNode[i] = malloc( sizeof(NODELIST *) * Col ); pppNode[1][0] = &Node; (可能最多5MB max)的文本文件中找到最后一个字符串。我找到了所有事件,但是如何从特定位置打印最后/最后一次?

这是我的代码:

10MB

以下是我的文字文件的示例数据:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;
    string line;
    char* str = "A-B";
    file.open("test.txt");
    unsigned int currline = 0;
    while(getline(file, line)) {
        currline++;
        if (line.find(str, 0) != string::npos) {
            cout << "found your search term: " << str << " at the " <<"line no.: " << currline << endl;
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在每次迭代时将找到的文本分配给变量将覆盖变量内容并在循环结束后打印它将仅打印最后一次出现:

这样的事情应该做:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;
    string line;
    string found = "Nothing found";
    char* str = "A-B";
    file.open("test.txt");
    unsigned int currline = 0;
    while(getline(file, line)) {
        currline++;
        if (line.find(str, 0) != string::npos) {
            found = line;
        }
    }
    cout << found << endl;
    return 0;
}