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