一、IO标准库的条件状态
操作
|
含义
|
stream::iostate
| 条件状态对应的类型名称。 |
stream::badbit
|
stream::iostate类型的值,用于指出被破坏的流。
|
stream::failbit
| stream::iostate类型的值,用于指出失败的IO操作。 |
stream::eofbit
|
stream::iostate类型的值,用于指出流已经到达EOF。
|
s.eof()
|
如果设置了流s的
eofbit值,则返回true。
|
s.fail()
|
如果设置了流s的
failbit值,则返回true。
|
s.bad()
|
如果设置了流s的
badbit值,则返回true。
|
s.good()
|
如果流s处于有效状态(即:
eofbit、failbit、badbit均未被设置),则返回true。
|
s.clear()
|
将流s中的所有状态都重新设置为有效状态。
|
s.clear(flag)
|
将
流s中的指定状态都重新设置为有效状态。flag的类型为stream::iostate。
|
s.setstate(flag)
|
给流s添加指定条件。flag的类型是
stream::iostate。
|
s.rdstate()
|
返回流s的当前条件。返回值的类型是
stream::iostate。
|
习题8.3&8.4:流读取操作
#include <iostream>
#include <stdexcept>
using namespace std;
istream& read_stream(istream& in)
{
int ival;
while (in >> ival, !in.eof())
{
if (in.bad())
{
throw runtime_error("IO stream corrupted!");
}
if (in.fail())
{
cout << "Read fail, try again." << endl;
in.clear();
in.ignore(2, ' ');
continue;
}
// ival is ok, process it
cout << ival << " ";
}
cout << endl;
in.clear();
return in;
}
int main()
{
double dval;
read_stream(cin);
cout << "read_stream() finish." << endl;
cin >> dval;
cout << dval << endl;
return 0;
}
[chapter8]$ ./a.out
1 2 3 4 5 aaa bbb ccc 6 7 8 9 0
1 2 3 4 5 Read fail, try again.
Read fail, try again.
Read fail, try again.
Read fail, try again.
Read fail, try again.
Read fail, try again.
6 7 8 9 0
read_stream() finish.
1.02
1.02