String class, how to implement sprintf?

C

CJ

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
 
D

Davlet Panech

CJ said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top