打印 Stringstream 输出指针
下面的代码没有输出预期的“Bar”字符串,而是输出看起来像指针的内容。
#include <sstream>
#include <iostream>
int main()
{
std::stringstream Foo("Bar");
std::cout << Foo << std::endl; // Outputs "0x22fe80."
return 0;
}
这可以通过使用 Foo.str() 来解决,但它过去给我带来了一些问题。是什么导致了这种奇怪的行为?它记录在哪里?
Rather than outputting the expected string of "Bar"
, the following code outputs what looks to be a pointer.
#include <sstream>
#include <iostream>
int main()
{
std::stringstream Foo("Bar");
std::cout << Foo << std::endl; // Outputs "0x22fe80."
return 0;
}
This can be worked around by using Foo.str()
, but it's caused some issues for me in the past. What causes this strange behavior? Where is it documented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这一点也不奇怪。
流就是流,不是字符串。
可以通过成员函数
.str()
获取[string]缓冲区。这不是一个解决方法:它是 API。它应该记录在您的 C++ 标准库参考中,如果没有,那么您的参考不完整/错误。(稍微奇怪的是,您得到的是内存地址而不是编译错误;这是由于在 pre-C++ 中使用了safe bool idiom 0x 标准库,如另一个答案中所述。)
It's not strange at all.
A stream is a stream, not a string.
You can obtain the [string] buffer with the member function
.str()
. That's not a workaround: it's the API. It should be documented in your C++ standard library reference, and if it's not then your reference is incomplete/wrong.(What is slightly strange is that you get a memory address rather than a compilation error; that is due to the use of the safe bool idiom in the pre-C++0x standard library, as covered in another answer.)
std::stringstream
不应插入流中。这就是为什么你有str()
方法。您观察到的行为是由于
std::stringstream
转换为void*
,这是用于测试流的:在 C+ 中+11,此转换被显式转换为 bool 所取代,这导致此代码无法编译:
A
std::stringstream
is not supposed to be inserted in a stream. That's why you have thestr()
method.The behavior you're observing is due to the fact that
std::stringstream
has a conversion tovoid*
, which is what is used to test the stream:In C++11, this conversion is replaced by an explicit conversion to bool, which causes this code not to compile:
(1)使用 std::cout <<富<< std::endl;您应该确保 stringstream 已经重载“<<”。
(2)如果没有过载“<<” ,使用 std::cout <<富<< std::endl;可以输出 Foo 的地址。
(1)use std::cout << Foo << std::endl; you should make sure stringstream has already overload "<<".
(2)if there is not overload "<<" , use std::cout << Foo << std::endl; may output the Foo's address.