您的位置:首页 > 编程语言 > C语言/C++

c++ primer 学习笔记(3): IO

2016-05-18 14:56 337 查看

8.1 IO类

1.IO对象不能拷贝或赋值

<code class="hljs php has-numbering">ofstream out1,out2;
out1=out2;<span class="hljs-comment">//错误:不能对流对象赋值</span>
ofstream <span class="hljs-keyword">print</span>(ofstream);<span class="hljs-comment">//错误</span>
out2=<span class="hljs-keyword">print</span>(out2);<span class="hljs-comment">//错误</span></code>

因此通常以引用方式传递和返回流。读写一个对象通常会改变其状态,所以不能是const reference。

2.文件的输入输出

<code class="hljs cpp has-numbering"><span class="hljs-preprocessor">#include <iostream></span>
<span class="hljs-preprocessor">#include <fstream></span>
<span class="hljs-preprocessor">#include <string></span>
<span class="hljs-preprocessor">#include <vector></span>
<span class="hljs-preprocessor">#include<algorithm></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
ifstream& read(ifstream& in)
{
<span class="hljs-built_in">string</span> str;
<span class="hljs-stl_container"><span class="hljs-built_in">vector</span><<span class="hljs-built_in">string</span>></span>  vstr;
<span class="hljs-keyword">while</span> (getline(in,str),!in.eof())
{
vstr.push_back(str);
}
for_each(vstr.cbegin(),vstr.cend(),
[](<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span>& str){<span class="hljs-built_in">cout</span><<str<<endl;});
<span class="hljs-keyword">return</span> in;
}
<span class="hljs-keyword">int</span> main()
{
ifstream in(<span class="hljs-string">"test.txt"</span>);
read(in);
getchar();
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: