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

How to add something to a file line by line in C++?

假设我有这个 .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)

我该怎么做?

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

using inliner = std::istream_iterator<Line>;

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

结构 Line 声明需要 operator>> 基于 std::getline:

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;
    }
}

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