The following code snippet is meant to try and extract an integer from a string using a stringstream object and detect whether integer extraction was successful or not. The stringstream class inherits the >> operator to return a reference to an istream instance. How does failed integer extraction lead to myStream being equal to 0 while its str member is still strInput?
stringstream myStream(strInput);
if (myStream >> num){//successfull integer extraction}
else{//unsuccessfull integer extraction
cout<<myStream<<endl;
cout<<myStream.str().c_str()<<endl;}
There is an operator bool()
or operator void*()
for stream
, which returns (something like) !fail()
- or in case of void *
a NULL when it failed. So, if the stream hasn't failed, it's fine. The operator >>
returns a reference to the stream
object, so the compiler says "Hmm, can't compare a stream object to truth, let's see if we can make a bool
, or void *
from it, yes we can, so let's use that.
The answer is in the operator that converts std::ios
to void*
(replaced with an operator to convert basic_ios
to a bool
in C++11):
A stream object derived from ios can be casted to a pointer. This pointer is a null pointer if either one of the error flags (failbit or badbit) is set, otherwise it is a non-zero pointer.
This operator gets called when your stream is used in an if
, while
, or for
condition. There is also a unary !
operator for the cases when you need to write
if (!(myStream >> num)) {
...
}