几天前我在玩 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.

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

10-13 09:08