zoukankan      html  css  js  c++  java
  • 《c++ primer》chap8 The IO library 小结

    8.1 IO 类

    iostream 头文件:istream, ostream, iostream类

    fstream 头文件:ifstream, ofstream, fstream类,从istream...继承

    sstream 头文件:istringstream, ostringstream, stringstream类,从istream...继承

    若要输出 wchar_t 类型而不是 char, 则用 wcin, wcout, wcerr 而不是 cin, cout, cerr

    IO 对象无法赋值,或复制,但能以别名的方式作为函数参数或返回值,实现输入和输出。

    IO 对象的状态:

      iostate, 它有四个值 badbit(出错), failbit(失败), eofbit(文件末), goodbit(良好,值为0)

        eof(), fail(), bad(), good() 返回上面四个值

        clear() 重置

        clear(flags) 重置为 flags

        setstate(flags)

        rdstate() 返回 iostate的值

    输出对象的缓冲

      为了提高效率,计算机会整合若干次输出内容,放在缓冲区,缓冲区满了才输出一次。

      以下操作会清理缓冲区(全部输出)

        程序结束

        缓冲区满了

        输出endl

        cout<<unibuf; cerr的内容自动加了unibuf,所以 cerr 输出的所有内容立即输出

        cin, cerr 都与 cout 绑定,所以使用 cin, cerr 时 cout 都自动清理缓冲。

      注意,程序出错中断,并不会清理缓冲,可能一些中间输出信息在缓冲区,还没有输出。

    8.2 文件输入和输出

      因为 ifstream, ofstream, fstream 都是 继承自 istream, ostream, iostream,所以 iostream 中的操作,fstream的对象都可以用。

      例如 >>, <<, getline(istream, string)

      ifstream 对象可以如下打开文件

    ifstream in(ifile); //打开 file 文件
    ofstream out;
    out.open( ifile + ".copy" );

      关闭一个文件,才能打开另一个文件

    out.close();

      如果在一个函数中定义文件流对象,并打开文件,函数结束时会自动关闭这个文件。

      文件打开模式:

      in  读取内容

      out  写入内容

      app  追加内容

      ate  打开后定位到文件末尾

      trunc  在out模式下,删除原内容再写入

      binary  二进制读取/写入  

    ofstream out("file2", ofstream::app); //追加内容
    ofstream out("file1"); //默认out, trunc 模式

    8.3 string 流

    需要包括头文件 sstream。从一个 string 中读取内容,不是从文件中读取,所以叫做 in-memory IO

    以下链接中有较为详细的总结:

    https://blog.csdn.net/liitdar/article/details/82598039

    sstream strm; 
    sstream strm(s); // string 流对象 strm 中复制了一份 string s 的内容
    strm.str(); // 返回 strm 中储存的 string
    strm.str(s) // 将 s 中的内容复制进 strm 对象,不返回值
    strm.clear(); // 清空strm中的内容。重复使用strm时,必须strm.clear()一次。

    比如:

    sstream strm("morgan 2015 2034");
    string name, word;
    vector<string> phones;
    strm>>name;
    while(strm>>word)
        phones.push_back(word);
  • 相关阅读:
    收藏题(小试牛刀)
    博客园及相关学习地址收录
    迭代器和生成器
    字典访问的三种方法
    函数进阶(装饰器)
    函数进阶(闭包)
    wx小程序知识点(六)
    wx小程序知识点(五)
    wx小程序知识点(四)
    wx小程序知识点(三)
  • 原文地址:https://www.cnblogs.com/luyi07/p/12562254.html
Copyright © 2011-2022 走看看