首页 > 解决方案 > 使用输入 C++ 从 .txt 文件中打印 N 行

问题描述

我想制作一个从 .txt 读取行的程序,如下所示:

输入:文件名/要开始打印的行/要打印的最后一行数

在控制台中,它看起来像这样: text 10 30 (它将从 .txt 文件的第 10 行打印到第 30 行)

我设法打印了所有行,但不知道如何在范围内显示它们。我正在分享我的代码,但如果您知道更简单的方法 - 将不胜感激!

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

bool create_file_with_n_lines(string outfile, int n)
{
    ofstream of;
    int i;

    of.open(outfile.c_str());

    for(i = 0; i < n; i++){
        of << "line " << i << endl;
    }

    of.close();

    return true;
}

bool get_last_n_lines(string infile, int n)
{
    ifstream instream;
    instream.open(infile.c_str());

    vector<string> v;
    char line[256];
    int i = 0;

    if(n < 1){
        return false;
    }

    while(!instream.eof()){
        instream.getline(line, 256);
        cout << line << endl;
        if(i < n){
            v.insert(v.end(), line);
        }
        else{
            string str = line;
            if(str.size() != 0)
                v.at(i%n) = line;
        }

        i ++;
    }

    cout << "after processing" << endl;

    int j;
    i --;

    if(i > n){
        i = i % n;
        for(j = i; j < n; j ++){
            cout << v.at(j).c_str() << endl;
        }
    }

    for(j = 0; j < i; j ++){
        cout << v.at(j).c_str() << endl;
    }

    return true;
}

int main(int argc, char* argv[])
{
    string strfile = "out.txt";
    create_file_with_n_lines(strfile,12);
    get_last_n_lines(strfile,  5);

    return 0;
}

标签: c++

解决方案


我相信你多虑了。

要从 to 打印行ab从零开始),请跳过a行,然后打印下一b-a+1行。

void print_lines(string infile, int from, int to)
{
    ifstream instream(infile);
    int count = to - from + 1;
    std::string line;
    while (from-- && std::getline(instream, line))
    {
        // Intentionally left blank.
    }
    while (count-- && std::getline(instream, line))
    {
        std::cout << line << std::endl;
    }
}

推荐阅读