流的状态由 bad、fail、eof 和 good 操作提示。如果 bad、fail 或者 eof
中的任意一个为 true,则检查流本身将显示该流处于错误状态。类似地,如果
这三个条件没有一个为 true,则 good 操作将返回 true。
clear 和 setstate 操作用于改变条件成员的状态。clear 操作将条件重设
为有效状态。在流的使用出现了问题并做出补救后,如果我们希望把流重设为有
效状态,则可以调用 clear 操作。使用 setstate 操作可打开某个指定的条件,
用于表示某个问题的发生。除了添加的标记状态,setstate 将保留其他已存在
的状态变量不变。
流状态的查询和控制
可以如下管理输入操作
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
中的任意一个为 true,则检查流本身将显示该流处于错误状态。类似地,如果
这三个条件没有一个为 true,则 good 操作将返回 true。
clear 和 setstate 操作用于改变条件成员的状态。clear 操作将条件重设
为有效状态。在流的使用出现了问题并做出补救后,如果我们希望把流重设为有
效状态,则可以调用 clear 操作。使用 setstate 操作可打开某个指定的条件,
用于表示某个问题的发生。除了添加的标记状态,setstate 将保留其他已存在
的状态变量不变。
流状态的查询和控制
可以如下管理输入操作
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,直到到达文件结束符或者发生不可恢复的读取错误
为止。