Chapter 8. The IO Library

  • io类的继承关系图,io类对象不允许复制和赋值。流可以看成在内存里活动着的的一段数据,这样好理解些。

  • 条件状态

    • 所有流对象都包含一个条件状态成员
    • 看一个例子
    int ival;
    // read cin and test only for EOF; loop is executed even if there are other IO failures
    while (cin >> ival, !cin.eof()) {
        if (cin.bad())         // input stream is corrupted; bail out
            throw runtime_error("IO stream corrupted");
        if (cin.fail()) {                        // bad input
            cerr<< "bad data, try again";        // warn the user
            cin.clear(istream::failbit);         // reset the stream
            continue;                            // get next input
        }
        // ok to process ival
    }		
    

    cin.bad() 检查流是否被破坏,cin.fail()检查输入是否有效。这段代码目的是为了保证循环体中余下部分可以安全使用ival。

  • 输出缓冲区的管理

    • 输出缓冲区的刷新
    int ival;
    // read cin and test only for EOF; loop is executed even if there are other IO failures
    while (cin >> ival, !cin.eof()) {
        if (cin.bad())         // input stream is corrupted; bail out
            throw runtime_error("IO stream corrupted");
        if (cin.fail()) {                        // bad input
            cerr<< "bad data, try again";        // warn the user
            cin.clear(istream::failbit);         // reset the stream
            continue;                            // get next input
        }
        // ok to process ival
    }
    
    • unitbuf操纵符,就是每次写操作执行完了,都会刷新那个准备写到流里的buffer。例子
    cout << unitbuf << "first" << " second" << nounitbuf;
    等价于:
    cout << "first" << flush << " second" << flush;
    
      nounitbuf是设置回来,继续按照系统规则来刷新buffer。
    
    • 因为程序崩溃了不会刷新buffer,所有最好在输出的时候手动刷新,加一个endlorflush
    • 因为标准库把cin和cout绑在了一起,所以任何读输入流的尝试都将首先刷新其输出流关联的缓冲区。
    • tie函数,没看明白,似乎不怎么用。
  • 文件的输入和输出

    • ifstream,ofstream,fstream
    • 文件流与新文件重新绑定,需要将原来的关闭,不然会有错误。最好的做法是close(),clear()都调用一下。
    • 文件模式。是文件的熟悉而不是流的属性。
    • 写程序的时候,如果要频繁读写文件的话,最好自己写一个函数,使得更安全的使用文件操作。
  • 字符串流

    • stringstream类,每次>>的时候,会根据空格停止,所以可以读一行内容到istringstream对象里,然后再从这个对象里把每一个单词读出来,当然每个单词会用空格分开。
    • 这个类可以提供转换和格式化的功能。你可以把不同类型的数据<<到ostringstream对象里面,然后调用她的str()函数,就能得到一个保存了那段内容的string类了。相反,用>>读出istringstream对象里的string,就能将里面的数值型数据字符串恢复出来。
原文地址:https://www.cnblogs.com/arctanx/p/5227953.html