cout << stringstream
What do you think
holdBuff << getline(cin, stringIn);
is doing. The return type of getline
is a reference to the stream
being read (cin
) in this case. Since there's no <<
defined which
takes an std::istream
as second argument, the compiler tries different
conversions: in C++11, std::istream
has an implicit conversion to
bool
, and in earlier C++, an implicit conversion to std::ios*
, or
something similar (but the only valid use of the returned value is to
convert it to bool
). So you'll either output 1
(C++11), or some
random address (in practice, usually the address of the stream, but this
is not guaranteed). If you want to get the results of a call to
getline
into an std::ostringstream
, you need two operations (with a
check for errors between them):
if ( !getline( std::cin, stringIn ) )
// Error handling here...
holdBuff << stringIn;
Similarly, to write the contents of a std::ostringstream
,
std::cout << holdBuf.str() ;
is the correct solution. If you insist on using an std::stringstream
when an std::ostringstream
would be more appropriate, you can also do:
std::cout << holdBuf.rdbuf();
The first solution is preferable, however, as it is far more idiomatic.
In any case, once again, there is no <<
operator that takes any
iostream
type, so you end up with the results of the implicit
conversion to bool
or a pointer.
Yes, you are likely to see the address of the stringstream.
If you want to display the string it contains, try
cout << stream.str();