如何在C ++中逐行添加文件?

时间:2016-10-27 07:03:07

标签: c++ file c++11 edit

我们考虑一下这个.txt文件:

one
two
three

并且喜欢从中创建这样的文件:

<s> one </s> (1)
<s> one </s> (2)
<s> one </s> (3)
<s> two </s> (1)
<s> two </s> (2)
<s> two </s> (3)
<s> three </s> (1)
<s> three </s> (2)
<s> three </s> (3)

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用stream iterators首先将输入文件读入存储每行的std::vector

using inliner = std::istream_iterator<Line>;

std::vector<Line> lines{
    inliner(stream),
    inliner() // end-of-stream iterator
};

结构Line根据std::getline声明所需的operator>>

struct Line
{
    std::string content;

    friend std::istream& operator>>(std::istream& is, Line& line)
    {
        return std::getline(is, line.content);
    }
};

工作示例:

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

struct Line
{
    std::string content;

    friend std::istream& operator>>(std::istream& is, Line& line)
    {
        return std::getline(is, line.content);
    }
};

int main()
{
    std::istringstream stream("one\ntwo\nthree");

    using inliner = std::istream_iterator<Line>;

    std::vector<Line> lines{
        inliner(stream),
        inliner()
    };

    for(auto& line : lines)
    {
        int i = 1;
        std::cout << "<s> " << line.content << " </s> (" << i << ")" << std::endl;
    }
}

要完成工作,请更改文件流的字符串流,并将完成的结果输出到文件中。