tags:

views:

114

answers:

3

I use to write code like this:

void fun(char *buff, unsigned size)
{
    std::strstream str(buff, size);
    str << "hello world: " << 5;
}

so I can use stream output over an arbitrary buffer. I've found this technique both efficient (no allocations) and useful (streams!). Now that std::strstream is deprecated, how can I get the same speed+flexibility that I can get with this code?

+1  A: 

try:

#include <sstream>
std::stringstream str;
str << "hello world: " << 5;

Edit: Sorry, I think I over simplified your question. That functionality is one of the things removed when changing to sstream. Here is something similar (I think this works...):

#include <sstream>
void fun(char *buff, unsigned size)
{
    std::stringstream str;
    str << "hello world: " << 5;
    memcpy(buff, str.str().c_str(), size);
}
Adam W
I think the poster asked for a way of handling the memory buffer himself.
Mattias Nilsson
std::stringstream allocates as you write to it. He wants to supply a fixed size pre-allocated buffer.
Peter Alexander
@Mattias @Peter: Ah, I was simply thinking he missed the switch from strstream to stringstream. I'll make an update.
Adam W
This is also not what he's looking for, and defeats the purpose. In the OP code, `strstream` will *not* do any allocation, because it's using the buffer provided. Yours will.
GMan
@GMan: Yes I understand that, but I was trying to show how to achieve the same effect of filling a buffer using sstream without another library. I agree it is not the same as OP's code and is not as efficient.
Adam W
stringstream allocates, and then we need a copy. efficiency is lost there.
+4  A: 

The standard library doesn't provide that functionality. However, Boost does with its generic streams and array sources/sinks.

Boost Generic Stream
Boost Array Devices

char buff[size];
boost::stream<boost::array_sink> out(buff, size);
out << "Hello, world!";

(Code untested)

Peter Alexander
nice man thanks!
A: 

Now that std::strstream is deprecated, how can I get the same speed+flexibility that I can get with this code?

I think it was deprecated for a reason. I had numerous portability problems in past when dealing with case of stream reaching the end of the buffer. Lack of the unity probably triggered the deprecation in favor std::string using version.

Otherwise, it amuses me that you mention "speed" in context of iostreams and the "<<" operators. I did bunch of tests in past and iostreams simply cannot catch up with good ol' snprintf(). Making a function call for every element - the effect of "<<" operators - is taxing anyhow you look at it and would be always slower. That's the cost of strict type checks.

Dummy00001
Not if the functions called are inlined, test your code with full optimizations (-O2, -fast, etc.)