How can I detect whether the istream extraction failed like this?
string s("x");
stringstream ss(s);
int i;
ss >> std::ios::hex >> i;
EDIT -- Though the question title covers this, I forgot to mention in the body: I really want to detect whether the failure is due to bad formatting, i.e. parsing, or due to any other IO-related issue, in order to provide proper feedback (an malformed_exception("x") or whatever).
First off: thanks for the useful answers. However, after some investigation (cfr. cppreference) and verification, it seems that the one way to check for parse-failure only is by checking for the ios::failbit
flag, as in
const bool parsing_failed = (ss >> ios::hex >> i).rdstate() & ios::failbit ;
While both the suggested istream::operator!
and istream::operator bool
mingle failbit
and badbit
(cfr here and there on cplusplusreference).