开发者

Printing Stringstream Outputs Pointer

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开发者_如何学C(), but it's caused some issues for me in the past. What causes this strange behavior? Where is it documented?


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?

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


A std::stringstream is not supposed to be inserted in a stream. That's why you have the str() method.

The behavior you're observing is due to the fact that std::stringstream has a conversion to void*, which is what is used to test the stream:

if(Foo) { // this uses the conversion to void*
}

In C++11, this conversion is replaced by an explicit conversion to bool, which causes this code not to compile:

std::cout << Foo << std::endl;


(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜