C++ Primer PartII 标准库(二)IO库

    xiaoxiao2026-05-22  6

    8-12章,IO库,顺序容器,泛型算法,关联容器,动态内存

    不知道怎么总结,所以挑一些书上的内容出来=-=

    ——————————- 8 IO库 ———————————

    IO类:成员对象(流状态)和函数方法(流状态查询和管理)、缓冲区管理 文件输入输出:继承iostream,特有:构造函数、open()、close()、is_close() string流:继承iostream,特有:构造函数、str()、str(s)、istringstream和ostringstream的使用

    8.1 IO类

    IO类之间的继承关系图 istream、ostream作为基类, istream 派生出 ifstream、istringstream ; ostream 派生出 ofstream、ostringstream 同时由 istream与ostream 共同派生出 iostream iotream 派生出 fstream、stringstream 在上述关系中,加上w就是其宽字符的类,eg: wistream、wstringstream

    IO对象无拷贝或赋值 如果需要传递或返回IO对象,则用指针或引用。流对象不能作为形参或返回类型,读写流会IO对象会改变其状态,因此 不能const

    流条件状态 iostate // 定义条件状态 badbit // 被破坏的流,不可恢复(系统级故障) failbit // 失败的io操作,可恢复,如读int却输入了char eofbit // 流到达文件结束符

    流方法 s.eof()、s.fail()、s.bad()、s.good() s.clear()、s.clear(flag) s.setstate(flag):对应位为1,其他默认0 s.rdstate():返回值类型strm:iostate

    //输入管理 int iVal; while(cin >> iVal, ! cin.eof()) { if(cin.bad) throw runtime_error("IO stream corrupted!"); if(cin.fail()) { cerr << "bad data, try again"; cin.clear(istream::failbit); continue; } }

    缓冲区刷新的情况: 1. 正常结束 2. 缓冲区满需要刷新 3. endl显示刷新缓冲区 4. unitbuf设置流的内部状态,cout << unitbuf << "content" << nounitbuf 即时刷新缓冲区然后关闭 5. 一个流关联(tie)到另一个流,当读写被关联的流时,关联到流的缓冲区会被刷新。比如,cin、cerr和cout关联,所以调用cin、cerr会导致cout刷新缓冲区

    8.2 文件输入输出

    使用文件流对象 1. 构造函数 2. open、close方法 (fstream特有) 对已经打开的文件流调用open会失败,会导致failtbit被置位 文件模式 文件模式是文件属性,而不是流属性

    模式说明适用对象in以读模式打开ifstream、fstreamout以写模式打开,隐式清空文件流,相当于out|truncof、fapp每次写定位到文件末尾,相当于out|appof、ftrunc截断文件,显式清空已存在文件流of、fate打开后立刻定位到文件末尾if、of、fbinary二进制方式if、of、f

    8.3 string流

    // string 流对象的使用 string line,word; while(getline(cin,line)){ istringstream stream(line); while(stream >> word); } // stringstream 提供的转换和格式化 int iVal1 = 512; ostringstream formatMsg; // 写 formatMsg << "Val1: " << iVal1 << "\n"; // 读,字符串到int型的转换 istringstream inputIString(formatMsg.str());//读 string dump; inputIString >> dump >> iVal1 ; cout << iVal1 << endl
    转载请注明原文地址: https://ju.6miu.com/read-1309961.html
    最新回复(0)