using stringstream >> operator in if statement

允我心安 提交于 2019-12-01 05:38:57

问题


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;}

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/14804046/using-stringstream-operator-in-if-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!