nul*_*ter 5 c++ iterator exception istream
几天前,我正在研究 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;
}
Run Code Online (Sandbox Code Playgroud)
为什么在读取输入文件的最后一个字后总是引发失败位异常?
检测 EOF 条件的方法是读取直到发生故障(这会触发异常),然后检查故障原因。
扩展一下:当使用 >> 读取值后,流运算符 void* 返回 NULL 时,istream_iterator 变得无效。但为此,运算符 >> 必须设置失败位,因此引发异常。
| 归档时间: |
|
| 查看次数: |
1625 次 |
| 最近记录: |