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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值