几天前,我正在研究 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
每当读取操作无法提取任何字符时设置,无论这是因为它是否到达 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)