c++ - 输入流迭代器和异常

标签 c++ exception iterator 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;
}

为什么在读取输入文件的最后一个字后总是引发 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.

关于c++ - 输入流迭代器和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2363581/

相关文章:

java - 我应该在哪里放置 close() 方法?

java - 没有这样的元素异常(exception)吗?

python - 生成器合并排序的类似字典的可迭代对象

c++ - 迭代 std::deque 时删除元素时出现段错误

c++ - 在 Win32 中构建最新的 iconv 和 libxml2 二进制文件

c++ - 通过套接字传输大型阵列的最快方法

c++ - std::map 迭代器不在 MFC 应用程序中迭代

c++ - Visual Express 2012 C++ 错误 LNK2001

c# - 异常处理 : how granular would you go when it comes to argument validation?

python - 自定义迭代器类与生成器?