 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
CJ Guest
|
Posted: Tue Oct 28, 2003 9:25 pm Post subject: String class, how to implement sprintf? |
|
|
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
|
|
| Back to top |
|
 |
Davlet Panech Guest
|
Posted: Tue Oct 28, 2003 10:54 pm Post subject: Re: String class, how to implement sprintf? |
|
|
"CJ" <cj (AT) nospam (DOT) com> wrote
| Quote: |
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.
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|