" stringstream>>"的返回值是多少?

时间:2017-01-13 19:12:16

标签: c++ stringstream

" stringstream>>"的返回值是多少?例如," stringstream_obj>>的返回值int_obj&#34 ;.我知道返回类型仍然是流,因为" istream&运营商GT;> (int& val)"。但是它的价值是什么?具体来说,这是我的代码。

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main (void)
{
    stringstream sss(string("0"));
    int num;
    if (sss >> num) // don't understand here
        cout << "true" << endl;
    else 
        cout << "false" << endl;
    //output "true"    
    return 0;
}

作为评论,为什么输出为真? sss只包含1个字符。一旦&#34; sss&gt;&gt; num&#34;,返回&#34; stringstream&#34;应该有空的内容,因此括号的值应该是假的。

理解的,

2 个答案:

答案 0 :(得分:2)

正如您所说,

operator>>返回对流的引用。然后,在if的上下文中,流通过conversion operator转换为bool,其中包含:{/ p>

  

如果流没有错误,则为true,否则为false。

您已成功阅读“0”,因此该流没有错误,请再次阅读,您会看到该流有错误,if(sss)评估为false

答案 1 :(得分:0)

在c ++中,当>>与流一起使用时,它会返回

http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

在您的案例中,运算符&gt;&gt; sss >> num返回sss

(我假设您正在使用c ++ 11,它看起来像)

然后你的sss aka stringstream有一个bool operator 如果转换成功,则返回true

所以总结一下if语句更像是

if( convert sss to int and check if successful)
// success
else
// fail

这是你可以阅读的好讨论 http://www.cplusplus.com/forum/articles/6046/

相关问题