I can copy some ostringstream into a new char array like this:
std::ostringstream stream;
...
std::string str = stream.str();
size_t size = str.size();
char *target = new char[size];
memcpy(target,str.c_str(),size);
How about the performance? Is there a way to copy the data directly to the array Buffer?
I think it will look like:
size_t size = str.tellp();
char *target = new char[size];
stream.copyTo(target,size); //??
std::stringdirectly. You don't have to copy out of it to use it as a C string (at least in C++11, where it has guaranteed contiguous storage).std::stringessentially already contains that. There's a good answer on how to get at it for modification. It also turns out that C++17 added a non-const version ofdata()to give direct write access.std::strstream, which is deprecated, andstd::spanstream, which progressed to LWG at the last meeting, so it might be in C++20.