This works:
stringstream temp;
temp << i;
result_stream << transform(temp.str());
(transform
is a function that takes a string
and returns a string
; i
is an int
). However, my attempt to let C++11 create a temporary object without a name didn't work:
result_stream << transform((stringstream() << i).str());
I thought it would work, since the second <<
should just return the first argument and I'd be able to use str()
on that. But I get this error:
error: 'class std::basic_ostream<char>' has no member named 'str'
I'm using g++ 4.8.1 (MinGW-W64).
Is there a way to accomplish this (i.e. write code like this using an unnamed temporary)? (The above code is a bit simplified, and the actual code involves using <<
on arguments other than int
.)
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
How to Perform Extraction or Read Operation in StringStream in C++ Like the insertion, we can also perform extraction on StringStream in C++, like the cin >> operator. We can again do this by using the >> operator or the str() function.
The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
This doesn't work because the second <<
is std::ostream &operator<<(std::ostream &, int);
and so the return type is ostream&
which has no member str()
.
You would have to write:
result_stream << transform( static_cast<stringstream &>(stringstream() << i).str() );
Update (2019): According to LWG 1203 the standard may be changed in future (and one major implementation already has) so that this code no longer works, and a simpler code works instead. See this question for detail.
In the interim period, apparently the following works on both old and new:
result_stream << transform( static_cast<stringstream &>(stringstream().flush() << i).str() );
// ^^^^^^^^
This should not be a performance penalty since flushing an empty stream has no effect...
operator<<()
returns a reference to the base class std::ostream
contained within the std::stringstream
. The base class doesn't contain the str()
method. You can cast it back down to a std::stringstream&
:
result_stream << transform(static_cast<std::stringstream&>(std::stringstream() << i).str());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With