2013-04-02 45 views
0

下面是我正在運行的代碼和相應的輸出。std :: ostream tellp()在VS2010中給出錯誤的輸出

#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的對象創建的大小?

+0

創建'的std :: ostream'對象的大小實際上是'的sizeof(字符串流)',但是這可能不是你要找的東西。 – dyp

回答

0

它不會給你一個「錯誤」的輸出/值。 tellp使用rdbuf()->pubseekoff,它將呼叫轉接到virtual seekoff。按照C++標準中的定義,basic_streambuf實現只返回-1。您需要在您的ostreambuf類中爲此方法提供自己的實現。

cppreference: basic_streambuf::pubseekof