[英]Input stream iterators and exceptions
几天前,我正在玩istream迭代器和异常处理,我遇到了这种好奇心:
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc < 2) {
cout << argv[0] << " <file>" << endl;
return -1;
}
try {
ifstream ifs(argv[1]);
ifs.exceptions(ios::failbit | ios::badbit);
istream_iterator<string> iss(ifs), iss_end;
copy(iss, iss_end, ostream_iterator<string>(cout, "\n"));
}
catch (const ios_base::failure& e) {
cerr << e.what() << endl;
return -2;
}
return 0;
}
为什么在读取输入文件的最后一个单词后总会引发failbit异常?
只要读取操作无法提取任何字符,就会设置failbit
,无论这是因为它是否触及EOF。
stringstream ss ("foo");
string s;
int i;
ss >> i; // sets failbit because there is no number in the stream
ss.clear();
ss >> s; // sets eofbit because EOF is hit
ss.clear();
ss >> s; // sets eofbit and failbit because EOF is hit and nothing is extracted.
通过读取检测EOF条件直到失败 - 触发异常 - 然后检查失败的原因。
要展开:当使用>>读取值时,istream_iterator变为无效,流运算符void *返回NULL。 但为此,运算符>>必须设置失败位,因此提高异常。
好问题。 能够在该呼叫中捕获其他故障会很好,但是当它达到eof时它会正常继续。
也就是说,之前我没有使用过流的异常。 我认为你可以复制并检查流的状态,然后检测其他错误,例如:
ifstream ifs(argv[1]);
if (!ifs) {
cerr << "Couldn't open " << argv[1] << '\n';
return -1;
}
//ifs.exceptions(ios::failbit | ios::badbit);
istream_iterator<std::string> iss(ifs), iss_end;
copy(iss, iss_end, ostream_iterator<std::string>(cout, "\n"));
if (!ifs.eof()) {
cerr << "Failed to read the entire file.\n";
return -2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.