Leo
Leo

Reputation: 1223

c++ stringstream to ostream to string

I would like to be able to do:

foo(stringstream()<<"number = " << 500);

EDIT: single line solution is crucial since this is for logging purposes. These will be all around the code.

inside foo will print the string to screen or something of the sort.

now since stringstream's operator<< returns ostream&, foo's signature must be:

foo(ostream& o);

but how can I convert ostream& to string? (or char*). Different approaches to achieving this use case are welcome as well.

Upvotes: 6

Views: 23206

Answers (8)

Interarticle
Interarticle

Reputation: 385

If you don't mind using macros functions, you can make the logging function accept const string&, and use the following macro

#define build_string(expr) \
    (static_cast<ostringstream*>(&(ostringstream().flush() << expr))->str())

And suppose you foo has signature void foo(const string&), you only need the one-liner

foo(build_string("number = " << 500))

This was inspired by James Kanze's answer about static_cast and stringstream.flush. Without the .flush() the above method fails with unexpected output.

Please note that this method should not leak memory, as temporary values, whether in the pointer form or not, are still allocated on the stack and hence destroyed upon return.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

I would suggest you to use this utility struct:

struct stringbuilder
{
   std::stringstream ss;
   template<typename T>
   stringbuilder & operator << (const T &data)
   {
        ss << data;
        return *this;
   }
   operator std::string() { return ss.str(); }
};

And use it as:

void f(const std::string & s );

int main() 
{
  char const *const pc = "hello";

  f(stringbuilder() << '{' << pc << '}' );

  //this is my most favorite line
  std::string s = stringbuilder() << 25  << " is greater than " << 5 ;
}

Demo (with few more example) : http://ideone.com/J995r

More on my blog : Create string on the fly just in one line

Upvotes: 8

James Kanze
James Kanze

Reputation: 153919

The obvious solution is to use dynamic_cast in foo. But the given code still won't work. (Your example will compile, but it won't do what you think it should.) The expression std::ostringstream() is a temporary, you can't initialize a non-const reference with a temporary, and the first argument of std::operator<<( std::ostream&, char const*) is a non-const reference. (You can call a member function on a temporary. Like std::ostream::operator<<( void const* ). So the code will compile, but it won't do what you expect.

You can work around this problem, using something like:

foo( std::ostringstream().flush() << "number = " << 500 );

std::ostream::flush() returns a non-const reference, so there are no further problems. And on a freshly created stream, it is a no-op. Still, I think you'll agree that it isn't the most elegant or intuitive solution.

What I usually do in such cases is create a wrapper class, which contains it's own std::ostringstream, and provides a templated member operator<< which forwards to the contained std::ostringstream. Your function foo would take a const reference to this—or what I offen do is have the destructor call foo directly, so that the client code doesn't even have to worry about it; it does something like:

log() << "number = " << 500;

The function log() returns an instance of the wrapper class (but see below), and the (final) destructor of this class calls your function foo.

There is one slight problem with this. The return value may be copied, and destructed immediately after the copy. Which will wreck havoc with what I just explained; in fact, since std::ostringstream isn't copyable, it won't even compile. The solution here is to put all of the actual logic, including the instance of std::ostringstream and the destructor logic calling foo in a separate implementation class, have the public wrapper have a boost::shared_ptr to it, and forward. Or just reimplement a bit of the shared pointer logic in your class:

class LogWrapper
{
    std::ostringstream* collector;
    int* useCount;
public:
    LogWrapper()
        : collector(new std::ostringstream)
        , useCount(new int(1))
    {
    }

    ~LogWrapper()
    {
        -- *useCount;
        if ( *useCount == 0 ) {
            foo( collector->str() );
            delete collector;
            delete useCount;
        }
    }

    template<typename T>
    LogWrapper& operator<<( T const& value )
    {
        (*collector) << value;
        return *this;
    }
};

Note that it's easy to extend this to support optional logging; just provide a constructor for the LogWrapper which sets collector to NULL, and test for this in the operator<<.

EDITED:

One other thing occurs to me: you'll probably want to check whether the destructor is being called as a result of an exception, and not call foo in that case. Logically, I'd hope that the only exception you might get is std::bad_alloc, but there will always be a user who writes something like:

log() << a + b;

where the + is a user defined overload which throws.

Upvotes: 8

David Hammen
David Hammen

Reputation: 33126

A couple of options other than the nice proxy solution just presented by Frerich Raabe:

  • Define a static string stream variable in the header that defines the logging function and use the comma operator in your invocation of the logging function so that this variable is passed rather than the ostream& returned by the stream insertion operator. You can use a logging macro to hide this ugliness. The problem with this solution is that it is a bit on the ugly side, but this is a commonly used approach to logging.

  • Don't use C++ I/O. Use a varargs C-style solution instead. Pass a format string as the first argument, with the remaining arguments being targets for that format string. A problem with this solution is that even if your compiler is smart enough to ensure that printf and its cousins are safe, the compiler probably won't know that this new function is a part of the printf family. Nonetheless, this is also a commonly used approach.

Upvotes: 1

You can create a small wrapper around std::ostringstream that will convert back to std::string on use, and have the function take a std::string const &. The first approach to this solution can be found in this answer to a different question.

On top of that, you can add support for manipulators (std::hex) if needed.

Upvotes: 0

Frerich Raabe
Frerich Raabe

Reputation: 94329

You could use a proxy object for this; this is a bit of framework, but if you want to use this notation in a lot of places then it may be worth it:

#include <iostream>
#include <sstream>

static void foo( std::string const &s )
{
    std::cout << s << std::endl;
}

struct StreamProxy
{
    std::stringstream stream;
    operator std::string() { return stream.str(); }
};

template <typename T>
StreamProxy &operator<<( StreamProxy &s, T v )
{
    s.stream << v;
    return s;
}

static StreamProxy make_stream()
{
    return StreamProxy();
}

int main()
{
    foo( make_stream() << "number = " << 500 );
}

This program prints

number = 500

The idea is to have a little wrapper class which can be implicitely converted into a std::string. The << operator is simply forwarded to the contained std::stringstream. The make_stream() function is strictly speaking not necessary (you could also say StreamProxy(), but I thought it looks a bit nicer.

Upvotes: 3

hochl
hochl

Reputation: 12930

Since you're converting to string anyways, why not

void foo(const std::string& s)
{
    std::cout << "foo: " << s << std::endl;
}

...

std::stringstream ss;
ss << "number = " << 500;
foo(ss.str());

Upvotes: 0

Constantinius
Constantinius

Reputation: 35059

This is not possible. As the name ostream implies, it is used for output, for writing to it. You could change the parameter to stringstream&. This class has the method str() which returns a std::string for your use.

EDIT I did not read the issue with operator << returning ostream&. So I guess you cannot simply write your statements within the functions argument list but have to write it before.

Upvotes: 0

Related Questions