0

I was using the simple file-slurp and I decided to add some error checking. I was surprised that an empty file gives an error. This doesn't happen with every empty sequence either, "" works fine. I also verified that rdbuf() is returning a non-null pointer.

#include <iostream>
#include <sstream>
using namespace std;

int main(int, char**){
    istringstream in(""); // Succeeds if non-empty
    stringstream sstr;
    if (sstr << in.rdbuf()) { // Succeeds if I replace in.rdbuf() with ""
        cout << "Read Successful\n";
    }else{
        cout << "Read Failed\n";
    }
}
Community
  • 1
  • 1
Eponymous
  • 4,271
  • 3
  • 37
  • 40

1 Answers1

1

It sets failbit because the standard requires it. (I feel foolish now. I thought I might have been doing something wrong.) Section 27.7.3.6.3.9 of the November 2014 Draft says:

If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure (27.5.5.4)).

Why the committee decided to make this behavior different from other sequence insertions (like char* and string) which do not consider insertion of nothing to be a failure is still a mystery. But I now know it is not a failure indicating misuse of the object.

Eponymous
  • 4,271
  • 3
  • 37
  • 40