如何在C中逐行添加文件?
发布时间:2020-12-16 06:52:41 所属栏目:百科 来源:网络整理
导读:我们考虑一下这个.txt文件: onetwothree 并且喜欢从中制作这样的文件: 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首先将
我们考虑一下这个.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声明所需的运算符>>基于 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.content); } }; int main() { std::istringstream stream("onentwonthree"); 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; } } 要完成工作,请更改文件流的字符串流,并将完成的结果输出到文件中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |