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

来源:互联网 发布:如何成为淘宝一件代发 编辑:程序博客网 时间:2024/06/02 02:00

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>

0 0
原创粉丝点击