【问题标题】:How to add something to a file line by line in C++?如何在 C++ 中逐行向文件添加内容?
【发布时间】:2017-03-09 18:15:40
【问题描述】:

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

我该怎么做?

【问题讨论】:

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


【解决方案1】:

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

using inliner = std::istream_iterator<Line>;

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

std::getline 的基础上使用Line 声明需要operator&gt;&gt; 的结构:

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

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

【讨论】:

  • 非常感谢!不幸的是,我有 11+ 的声誉,我不能给你的帖子打正分。但我会在我达到 15 岁时这样做。
猜你喜欢
  • 2019-10-23
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2014-06-13
  • 2022-08-22
  • 1970-01-01
  • 2011-11-08
  • 2020-08-15
相关资源
最近更新 更多