Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istream extraction operator: how to detect parse failure?

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).

like image 658
xtofl Avatar asked Dec 13 '11 12:12

xtofl


1 Answers

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.

like image 117
01d55 Avatar answered Nov 15 '22 04:11

01d55