Using stringstream >> operator in if statement

The following code snippet is intended to try and extract an integer from a string using a stringstream object and determine if the extraction was successful or not. The stringstream class inherits the → operator to return a reference to an istream instance. How does a failed integer retrieval result in myStream being 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;}

      

+3


source to share


2 answers


There is operator bool()

either operator void*()

for stream

that returns (something like) !fail()

- or in case the void *

value is NULL, if it fails. This way, if the thread didn't fail, everything is fine. operator >>

returns a reference to the object stream

, so the compiler says, "Hmm, I can't compare the stream object with the truth, let's see if we can make it out of it bool

or void *

, yes we can, so we'll use that."



+4


source


The answer is what converts std::ios

tovoid*

(replaces to for converting basic_ios

to bool

in C ++ 11
):

A stream object obtained from ios can be passed to a pointer. This pointer is a null pointer if one of the error flags (failbit or badbit) is set, otherwise it is a non-null pointer.



This operator is called when your thread is used in conditions if

, while

or for

. There is also a unary operator !

for when you need to write

if (!(myStream >> num)) {
    ...
}

      

+1


source







All Articles