Search code examples
c++stringstringstreamboost-iostreams

Why stringstream::str() truncates string?


I have stringstream object. It is filled through

stringstream ss;
boost::iostreams::copy(inp,ss);

from

boost::iostreams::filtering_streambuf<boost::iostreams::input> inp;

and actually holds ungzipped file within.

Now if i flush stringstream content to file with

std::ofstream ofs(path_to_file,std::ios_base::out|std::ios_base::binary);
ofs << ss.rdbuf();

everything is ok. File is filled with complete correct data.

But if i instead of flushing to file construct string like this

std::string s = ss.str();

content is truncated somewhere in the middle. It is not a persistent error, and it obviously depends on content of string buffer.

The content is HTML file in several languages.

What can it be? Thanks.


Solution

  • How are you determining that the content is truncated? A stringstream can contain null characters and std::string s = ss.str() will copy those null characters and the characters after it to the std::string object.

    However, if you then use functions that treat the std::string object's contents as a C style string, it will appear truncated:

    #include <sstream>
    #include <string>
    #include <iostream>
    #include <ostream>
    #include <string.h>
    
    using namespace std;
    
    stringstream ss;
    
    int main()
    {
        ss << 'a' << 'b' << 'c' << (char) '\0' << '1' << '2' << '3';
    
        string s = ss.str();
    
        cout << s.size() << endl;
        cout << s.c_str() << " C string length: " << strlen(s.c_str()) << endl;
        cout << s << endl;
    }
    

    produces the following output:

    7
    abc C string length: 3
    abc 123