0

Below is the code i am running and corresponding output.

    #include<iostream>
    #include <sstream>
    #include <strstream>
    #include <streambuf>

    template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type,std::char_traits<char_type> >
{
 ostreambuf(char_type* buffer, std::streamsize bufferLength)
{
    // set the "put" pointer the start of the buffer and record it's length.
    setp(buffer, buffer + bufferLength);
}
};


int main()            
{
 char strArr[]    = "Before-1";
 char stringArr[] = "Before-2";

 std::strstream strStream(strArr,sizeof(strArr));

 ostreambuf<char> ostreamBuffer(stringArr, sizeof(stringArr));
 std::ostream stringStream(&ostreamBuffer);

  const std::streampos posStringBefore = stringStream.tellp();

   std::cout << "Before: "
                                    << "strArr = " 
                                    << strArr 
                                    << " & "
                                    << "stringArr = "
                                    << stringArr
                                    << std::endl;

            std::cout << "Before: " << "posStringBefore = "
                                    << posStringBefore
                                    << std::endl;

            // -------------------------
            strStream << "After-1";
            stringStream << "After-2";
            const std::streampos posStringAfter = stringStream.tellp(); 

            std::cout << "After : "
                                    << "strArr = " 
                                    << strArr 
                                    << " & "
                                    << "stringArr = "
                                    << stringArr
                                    << std::endl;

            std::cout << "After : " << "posStringAfter = "
                                    << posStringAfter
                                    << std::endl;



            return 0;
}

This is the o/p on VS2010 :

 Before: strArr = Before-1 & stringArr = Before-2
 Before: posStringBefore = -1
 After : strArr = After-11 & stringArr = After-22
 After : posStringAfter = -1

In reference to link Setting the internal buffer used by a standard stream (pubsetbuf)

How to get the size of std::ostream object created?

Community
  • 1
  • 1
  • The size of the `std::ostream` object created is actually `sizeof(stringStream)`, but that's probably not what you're looking for. – dyp Apr 02 '13 at 12:23

1 Answers1

0

It doesn't give you a "wrong" output/value. tellp uses rdbuf()->pubseekoff which relays the call to virtual seekoff. The basic_streambuf implementation simply returns -1 as defined in the C++ standard. You need to provide an own implementation for this method in your ostreambuf class.

See cppreference: basic_streambuf::pubseekof

dyp
  • 38,334
  • 13
  • 112
  • 177