以下是我正在运行的代码和相应的输出。
#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 :(得分:0)
它不会给你一个“错误”的输出/值。 tellp
使用rdbuf()->pubseekoff
将呼叫转发给virtual seekoff
。 basic_streambuf
实现只返回C ++标准中定义的-1
。您需要在ostreambuf
类中为此方法提供自己的实现。