Could I use stringstream as a memory stream like `MemoryStream` in C#?

Amir Saniyan picture Amir Saniyan · Nov 24, 2012 · Viewed 10k times · Source

In C/C++, strings are NULL terminated.

Could I use stringstream as a memory stream like MemoryStream in C#?

Data of memory streams may have \0 values in the middle of data, but C++ strings are NULL terminated.

Answer

Dietmar Kühl picture Dietmar Kühl · Nov 24, 2012

When storing character sequences in a std::string you can have included null characters. Correspondingly, a std::stringstream can deal with embedded null characters as well. However, the various formatted operations on streams won't pass through the null characters. Also, when using a built-in string to assign values to a std::string the null characters will matter, i.e., you'd need to use the various overloads taking the size of the character sequence as argument.

What exactly are you trying to achieve? There may be an easier approach than traveling in string streams. For example, if you want to read the stream interface to interact with a memory buffer, a custom stream buffer is really easy to write and setup:

struct membuf
    : std::streambuf 
{
        membuf(char* base, std::size_t size) {
        this->setp(base, base + size);
        this->setg(base, base, base + size);
    }
    std::size_t written() const { return this->pptr() - this->pbase(); }
    std::size_t read() const    { return this->gptr() - this->eback(); }
};

int main() {
    // obtain a buffer starting at base with size size
    membuf       sbuf(base, size);
    std::ostream out(&sbuf);
    out.write("1\08\09\0", 6); // write three digits and three null chars
}