我们考虑一下这个.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)
我该怎么做?
答案 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;
}
}
要完成工作,请更改文件流的字符串流,并将完成的结果输出到文件中。