"CJ" <cj@nospam.co m> wrote in message
news:zt******** ************@gi ganews.com...
Ok, I've got a string class that stores the data in a dynamically
allocated "char* m_pData" variable. I'd like to write a member function similiar to
"sprintf" for this class.
When implementing this member function, I'd like to just call "sprintf"
under the covers. The problem is, that I dont' know how large the
resulting string will be and thus I don't know how much space I'll need to allocate
for my m_pData pointer.
Is there any easy what to do this?
Thanks!
-CJ
Many environments include a (non-standard) function called "snprintf /
vsnprintf". It allows you to provide the maximum length of your buffer, and
returns a special value if the buffer is too small. You can call that
function repeteadly allocating larger and larger amounts of memory until the
whole message fits in the buffer. It'll be a little slower, but it'll work.
I guess you could also open a dummy file [like "/dev/null" (UNIX), or "NUL"
(DOS, Windows), or just a normal temporary file], fprintf into it, grab the
return value, allocate that amount of memory, and then call the normal
sprintf. This might be even slower.
Note: printf() & friends return the number of characters they emitted.
D.