国际字符的支持
表 8.2. IO 标准库的条件状态
strm::iostate |
机器相关的整型名,由各个 iostream 类定义,用于定义条件状态 |
strm::badbit | strm::iostate value used to indicate that a stream is corrupted. strm::iostate 类型的值,用于指出被破坏的流 |
strm::failbit | strm::iostate value used to indicate that an IO operation failed. strm::iostate 类型的值,用于指出失败的 IO 操作 |
strm::eofbit | strm::iostate value used to indicate the a stream hit end-of-file. strm::iostate 类型的值,用于指出流已经到达文件结束符 |
s.eof() | true if eofbit in the stream s is set. 如果设置了流 s 的 eofbit 值,则该函数返回 true |
s.fail() | true if failbit in the stream s is set. 如果设置了流 s 的 failbit 值,则该函数返回 true |
s.bad() | true if badbit in the stream s is set. 如果设置了流 s 的 badbit 值,则该函数返回 true |
s.good() | true if the stream s is in a valid state. 如果流 s 处于有效状态,则该函数返回 true |
s.clear() | Reset all condition values in the stream s to valid state. 将流 s 中的所有状态值都重设为有效状态 |
s.clear(flag) | Set specified condition state(s) in s to valid. Type of flag is strm::iostate. 将流 s 中的某个指定条件状态设置为有效。flag 的类型是 strm::iostate |
s.setstate(flag) | Add specified condition to s. Type of flag is strm::iostate. 给流 s 添加指定条件。flag 的类型是 strm::iostate |
s.rdstate() | Returns current condition of s as an strm::iostate value. 返回流 s 的当前条件,返回值类型为 strm::iostate |
badbit 标志着系统级的故障,如无法恢复的读写错误。如果出现了这类错误,则该流通常就不能再继续使用了。如果出现的是可恢复的错误,如在希望获得数值型数据时输入了字符,此时则设置 failbit 标志,这种导致设置 failbit 的问题通常是可以修正的。eofbit 是在遇到文件结束符时设置的,此时同时还设置了 failbit。
条件状态的访问
rdstate 成员函数返回一个 iostate 类型值,该值对应于流当前的整个条件状态:
// remember current state of cin istream::iostate old_state = cin.rdstate(); cin.clear(); process_input(); // use cin cin.clear(old_state); // now reset cin to old state
输出缓冲区的刷新
我们的程序已经使用过 endl 操纵符,用于输出一个换行符并刷新缓冲区。除此之外,C++ 语言还提供了另外两个类似的操纵符。第一个经常使用的 flush,用于刷新流,但不在输出中添加任何字符。第二个则是比较少用的 ends,这个操纵符在缓冲区中插入空字符 null,然后后刷新它:
cout << "hi!" << flush; // flushes the buffer; adds no data cout << "hi!" << ends; // inserts a null, then flushes the buffer cout << "hi!" << endl; // inserts a newline, then flushes the buffer