【IO】IO库(一)流简介

本文详细介绍了C++标准库中的IO流概念,包括各种IO流类的定义和用途,如istream、ostream及其派生类。文章还深入探讨了IO流的条件状态,如badbit、failbit和eofbit,以及如何检查和重置这些状态。此外,还讲解了缓冲区刷新的时机,帮助开发者理解并控制输出流的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IO库类型和头文件
iosteam头文件中定义了:
              istream(从流中读取);//cin
              ostream(写到流中);//cout;cerr;clog
              iostream(对流进行读写,从istream和osteam派生而来)


fsteam头文件中定义了:
              ifstream(从文件中读取,由istream派生而来);
              ofstream(写到文件中去,由ostream派生而来);
              fstream(对文件进行读写,由iostream派生而来);


ssteam头文件中定义了: 
              istringstream(从string对象中读取,由istream派生而来);
              ostringstream(写到string对象中去,由ostream派生而来);
              stringstream(对string对象进行读写,由iostream派生而来);
IO对象无拷贝和赋值
    ofstream out1, out2;
    out1 = out2;//不能对流赋初值
    ofstream print(ofstream);//不能初始化ofstream参数
    out2=print(out2);//不能拷贝流对象
IO流的条件状态
//strm值得是流类 如iostream fstream等
    strm::iostate     // 机器相关的整型名,由各个iostream类定义,用于定义条件状态
    strm::badbit      // strm::iostate类型的值,用于指出被破坏的流
    strm::failbit       // strm::iostate类型的值,用于指出失败的IO操作
    strm::eofbit       // strm::iostate类型的值,用于指出流已经到达文件结束符
   
    s.eof()               // 如果流s的eofbit置位,则该函数返回true
    s.fail()               // 如果流s的failbit置位,则该函数返回true
    s.bad()              // 如果流s的badbit置位,则该函数返回true
    s.good()            // 如果流s处于有效状态,则该函数返回true
    s.clear()            // 将流s中的所有状态值都重设为有效状态
    s.clear(flag)      // 将流s中的某个指定条件状态设置为有效。flag的类型是strm::iostate
    s.setstate(flag) // 给流s添加指定条件。flag的类型是strm::iostate
    s.rdstate()        // 返回流s的当前条件,返回值类型为strm::iostate
  • 下面是一个简单的例子
    using namespace std;

    cout << iostream::goodbit << iostream::badbit << iostream::eofbit << iostream::failbit << endl;  // 输出 0 1 2 4
    iostream::iostate coutstate = cin.rdstate(); // 得到cin对象的原始状态值
    cout << coutstate << endl;  // 输出 0 cin的状态值是 std::iostream::goodbit
    int i;
    cin >> i; // 输入"123"
    cout << cin.rdstate() << endl;  // 输出 0 因为“123”可以被正确转成int并被存入i 所以cin的状态置为 std::iostream::goodbit
    cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 1 0 0 0
    cin >> i; // 输入"abd"
    cout << cin.rdstate() << endl;  // 输出 4  因为“abc”无法转成int存入i 所以cin的状态置为 std::iostream::failbit
    cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 0 0 1 0
    cin.clear(); // 重置cin状态为std::iostream::good 否则下面的cin << i 不会执行, 或者这样设置cin.clear(std::iostream::failbit)


    cin >> i; // 输入"568"
    cout << cin.rdstate() << endl;  // 输出 0 因为“568”可以被正确转成int并被存入i 所以cin的状态置为 std::iostream::good
    cout << cin.good() << cin.eof() << cin.fail() << cin.bad() << endl; // 输出 1 0 0 0
    

缓冲区的刷新

以下几种情况会引起缓冲区刷新

  • 缓冲区满时;
  • 执行flush语句;
  • 执行endl语句;
  • 关闭文件。

对于缓冲区刷新的理解可以有助于我们进行代码调试,未输出信息的语句在程序中不一定没有执行,有可能还在缓冲区,需要用flush或endl刷新输出,有助于我们尽快定位错误位置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值