简体   繁体   中英

using stringstream >> operator in if statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM