C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

String class, how to implement sprintf?

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
CJ
Guest





PostPosted: Tue Oct 28, 2003 9:25 pm    Post subject: String class, how to implement sprintf? Reply with 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
Back to top
Davlet Panech
Guest





PostPosted: Tue Oct 28, 2003 10:54 pm    Post subject: Re: String class, how to implement sprintf? Reply with quote




"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
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.