【问题标题】:Reading specific lines from a file in C++从 C++ 文件中读取特定行
【发布时间】:2018-05-12 20:04:34
【问题描述】:

以下代码用于循环遍历我之前打开的文件的最后十行。我认为seekg 函数是指二进制文件,并且只通过单个字节的数据,所以这可能是我的问题。

    //Set cursor to 10 places before end
    //Read lines of input
    input.seekg(10L, ios::end);

    getline(input, a);

    while (input) {
        cout << a << endl;
        getline(input, a);
    }

    input.close();
    int b;
    cin >> b;
    return 0;
}

我正在考虑做的另一种方法是计算文件最初循环的次数,减去十,然后通过文件计算该次数,然后输出下一个十,但这似乎广泛用于我想做的事情。

是否有类似seekg 的内容会转到文本文件中的特定行?还是应该使用我上面提出的方法?

编辑:我回答了我自己的问题:循环的东西就像另外 6 行代码。

【问题讨论】:

标签: c++ function file


【解决方案1】:

向后搜索换行符 10 次或直到文件光标小于或等于零。

【讨论】:

    【解决方案2】:

    如果你不关心最后 10 行的顺序,你可以这样做:

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <string>
    #include <cmath>
    
    int main() {
    
        std::ifstream file("test.txt");
        std::vector<std::string> lines(10);
    
        for ( int i = 0; getline(file, lines[i % 10]); ++i );
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      相关资源
      最近更新 更多