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).
if(! (ss >> std::ios::hex >> i) )
{
std::cerr << "stream extraction failed!" << std::endl;
}
It's just that easy.
ETA: Here's an example of how this test interacts with the end of a stream.
int i;
std::stringstream sstr("1 2 3 4");
while(sstr >> i)
{
std::cout << i << std::endl;
if(sstr.eof())
{
std::cout << "eof" << std::endl;
}
}
will print
1
2
3
4
eof
If you were to check sstr.eof()
or sstr.good()
in the while loop condition, 4 would not be printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With