I want to get rid of my "sprintf" call, so I wrote the following
example, in which I have two problems:
(1) why do I need to inherit from "streambuf", and not just use it as a
local in my "ToBuff" function (I get a protected constructor error)?
(2) I fail to get the output of the formatting in my C buffer, the
output of the program is:
string is: 100
buffer is: hello world
When I hoped to get:
string is: 100
buffer is: 100
note: the "ToString" function is not a real option where large buffers
should be allocated outside the class in "C style" code
the code:
///////////////////////////////////////////////////////////
#include <ostream>
#include <sstream>
#include <stdio.h>
#include <iostream>
using namespace std;
template <typename T>
class A : public streambuf
{
public:
A(const T& t) : m_value(t) {}
char* ToBuff(char* szBuff, int nSize)
{
pubsetbuf(szBuff, static_cast<streamsize>(nSize));
ostream os(this);
os << m_value << ends;
return szBuff;
}
string ToString() const
{
ostringstream ost(ostringstream::out);
ost << m_value << ends;
return ost.str();
}
private:
T m_value;
};
int main()
{
char buff[32]="hello world";
A<double> a(99.99999);
cout << "string is: " << a.ToString() << endl;
printf("buffer is: %s\n", a.ToBuff(buff,32));
return 0;
}