tobi303 tobi303 - 1 year ago 77
C++ Question

input to stringstream and convert to string in single statement. Possible without helper class?

I would like to write code like this:

std::string s = ??? << "asdf" << 123;

I am not sure what to place for the
to make it work. I can write a helper class:

#include <string>
#include <sstream>
#include <iostream>

struct Stringify {
std::stringstream o;
template <typename T>
Stringify& operator<<(const T& t){
o << t;
return *this;
operator std::string(){ return o.str(); }

int main(){
std::string s;
s = Stringify() << " test " << 123 << " asd";
std::cout << s << std::endl;

...but I am not able to do it wihtout the helper class. I tried different things, the nicest error message i got from this:

s = (std::stringstream() << "test" << 123 << " asd").str();

-> error: ‘class std::basic_ostream<char>’ has no member named ‘str’

I also tried more, but it just resulted in more complicated error messages.

Is it possible to do what I want without having to write a helper class? If not, is there any good reason why it isnt possible only with

Answer Source

Something like this:

std::string s = static_cast<std::ostringstream&>(std::ostringstream() << 7 << 10 << 12).str();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download