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

标签 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)

我该怎么做?

最佳答案

您可以使用 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;
    }
}

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

关于c++ - 如何在 C++ 中逐行向文件添加内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40278222/

相关文章:

C++11 无锁序列号生成器安全吗?

c++ - 抛出 "bad_alloc"的最常见原因是什么?

c++ - 非托管 C++ 获取当前进程 ID? (控制台应用程序)

c++ - 多维 vector 和指向 vector 的指针

c++ - 在头文件中执行 const std::string 的正确方法?

c++ - 安装Qt报错 "The procedure entry point _ZdaPvj could not be located in the dynamic link library C:\Qt\4.8.6\bin\qmake.exe"

c++ - 此 matlab 代码的 C++ 等效项是什么(fread matlab 与 fread C/C++)?

json - 如何将bash中的文件转换为json

c# - 处理/阅读这些文件的更好方法(HCFA 医疗 claim 表)

c++ - 我应该认为静态拷贝是成本高昂的吗?