Maxpm
Maxpm

Reputation: 25592

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

Upvotes: 2

Views: 6896

Answers (3)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234504

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;

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

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

Upvotes: 6

Jerry Zhang
Jerry Zhang

Reputation: 1236

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

Upvotes: 0

Related Questions