Search code examples
c++stlstringstream

Using a character array as a string stream buffer


I'm looking for a clean STL way to use an existing C buffer (char* and size_t) as a string stream. I would prefer to use STL classes as a basis because it has built-in safeguards and error handling.

note: I cannot use additional libraries (otherwise I would use QTextStream)


Solution

  • You can try with std::stringbuf::pubsetbuf. It calls setbuf, but it's implementation defined whether that will have any effect. If it does, it'll replace the underlying string buffer with the char array, without copying all the contents like it normaly does. Worth a try, IMO.

    Test it with this code:

    std::istringstream strm;
    char arr[] = "1234567890";
    
    strm.rdbuf()->pubsetbuf(arr, sizeof(arr));
    int i;
    strm >> i;
    std::cout << i;
    

    Live demo.