std :: ostream tellp()在VS2010中输出错误

时间:2013-04-02 11:51:35

标签: c++ visual-c++

以下是我正在运行的代码和相应的输出。

    #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;
}

这是VS2010上的o / p:

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

参考链接  Setting the internal buffer used by a standard stream (pubsetbuf)

如何创建std :: ostream对象的大小?

1 个答案:

答案 0 :(得分:0)

它不会给你一个“错误”的输出/值。 tellp使用rdbuf()->pubseekoff将呼叫转发给virtual seekoffbasic_streambuf实现只返回C ++标准中定义的-1。您需要在ostreambuf类中为此方法提供自己的实现。

请参阅cppreference: basic_streambuf::pubseekof