jeudi 1 juin 2023

Can an strstream directly use the buffer of a standard string

Given that strstream has the following constructor:

strstream( char* s, int n, std::ios_base::openmode mode);

I was wondering whether I can use the buffer underlying a standard string directly, in "read-only" mode of course to avoid weird side-effects from buffer reallocation:

std::string buffer("Dummy Data");
std::strstream ss(
  const_cast<char *>(buffer.data()), buffer.length(), std::ios_base::in);

std::string other;
ss >> other;
std::cout << other << std::endl;

To my surprise, the code above ends up making other an empty string. In the documentation there is an example where a C-array is used as a static buffer for strstream, so I'm wondering what's the reason it cannot use the contents of the std::string buffer?

Note: I can't use std::stringstream because the platform in question has a VS implementation that is limited to 4GB size as discussed here


UPDATE:

I see that using std::ios_base::app (as in the example) pretty much makes my code work. The biggest problem now (according to the comments I'm getting) is that strstream is long deprecated. Maybe there's something in boost iostreams that could help but idk much about that library.

Aucun commentaire:

Enregistrer un commentaire