How can I get the same strstream functions that are deprecated?

I use to write code as follows:

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

so I can use the output of the stream through an arbitrary buffer. I found this method to be both efficient (no allocation) and useful (threads!). Now that std :: strstream is out of date, how can I get the same speed + flexibility I can get with this code?

+3
source share
3 answers

The standard library does not provide this functionality. However, Boost uses its common streams and array sources / sinks.

Boost overall Boost Array Devices flow

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

(Code not verified)

+5
source

to try:

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

: , , . , sstream. - ( , ...):

#include <sstream>
void fun(char *buff, unsigned size)
{
    std::stringstream str;
    str << "hello world: " << 5;
    memcpy(buff, str.str().c_str(), size);
}
+2

, std:: strstream , + , ?

, . , , . , , std::string .

Otherwise, it amuses me that you mention “speed” in the context of iostreams and “<operators. I have done a bunch of tests in the past and iostreams just can’t catch up with a good ol snprintf (). Making a function call for each element is the effect of << operators are taxation, anyway, you look at it and it will always be slower.This is the cost of strict type checks.

-1
source

Source: https://habr.com/ru/post/1749096/


All Articles