"stringstream>>something" 的 return 值是多少?
What is the return value of "stringstream>>something"?
stringstream >> something
的 return 值是多少?例如,stringstream_obj >> int_obj
的 return 值。我知道 return 类型仍然是流,因为 istream& operator>> (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 个字符。一旦“sss >> num”,returned “stringstream”应该有空内容,因此括号的值应该是 false。
赞赏,
operator>>
returns 对流的引用,如您所说。然后,在 if
的上下文中,流通过 conversion operator 转换为 bool
,这给出:
true if the stream has no errors, false otherwise.
您成功读取了“0”,因此流没有错误,再次尝试读取一个,您将看到流有错误并且 if(sss)
计算为 false
。
在 C++ 中,通常当 >>
与流一起使用时,它 returns 本身
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
在你的情况下运算符>> 是 sss >> num
returns sss
(我假设你正在使用它看起来像的 c++11)
然后你的 sss aka stringstream 有一个 bool operator
如果转换成功,returns 为真
所以总而言之,if 语句更像是
if( convert sss to int and check if successful)
// success
else
// fail
这是一个很好的讨论,您可以阅读
http://www.cplusplus.com/forum/articles/6046/
stringstream >> something
的 return 值是多少?例如,stringstream_obj >> int_obj
的 return 值。我知道 return 类型仍然是流,因为 istream& operator>> (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 个字符。一旦“sss >> num”,returned “stringstream”应该有空内容,因此括号的值应该是 false。
赞赏,
operator>>
returns 对流的引用,如您所说。然后,在 if
的上下文中,流通过 conversion operator 转换为 bool
,这给出:
true if the stream has no errors, false otherwise.
您成功读取了“0”,因此流没有错误,再次尝试读取一个,您将看到流有错误并且 if(sss)
计算为 false
。
在 C++ 中,通常当 >>
与流一起使用时,它 returns 本身
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
在你的情况下运算符>> 是 sss >> num
returns sss
(我假设你正在使用它看起来像的 c++11)
然后你的 sss aka stringstream 有一个 bool operator 如果转换成功,returns 为真
所以总而言之,if 语句更像是
if( convert sss to int and check if successful)
// success
else
// fail
这是一个很好的讨论,您可以阅读 http://www.cplusplus.com/forum/articles/6046/