Jump to content
  • Advertisement
Sign in to follow this  
Skute

sprintf style function to tell you how big your buffer needs to be?

This topic is 4736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i need a function which will accept a variable number of arguments and will then tell me how big my buffer needs to be. does anyone know of one?

Share this post


Link to post
Share on other sites
Advertisement
That's one of the problems with sprintf. There is no way to determine the size of the buffer, unless you write some very sophisticated function for it.

You could use a stringstream(In case you're using C++). Include the <sstream> header and then do:

stringstream ss;
ss << somevar << othervar << somenumber;
string s = ss.str();


s now contains the end result.

EDIT: In case you're using custom classes to append at the end of the stream, you need to overload the operator << for the class.

Toolmaker

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
In C, you can use snprintf with size = 0.


Keep in mind that a lot of snprintf() implementations are non C99-compliant, so that even if snprintf is availble on your compiler, it may not work properly (ex: returning -1 instead of the number of bytes written if the buffer is smaller than the size would have been).

Share this post


Link to post
Share on other sites
Quote:
Original post by vNistelrooy
Wouldn't snprintf return 0?


A C99-compliant snprintf() function returns the number of characters that would have been written, not the number of characters actually written.

Share this post


Link to post
Share on other sites
I use this:

#ifdef __GCC__
#define _vscprintf(format, arglist) vsnprintf(0, 0, format, arglist)
#endif

inline int csprintf(const char* format, ...)
{
va_list argPtr;
va_start(argPtr, format);
int ret = _vscprintf(format, argPtr);
va_end(argPtr);
return ret;
}

Share this post


Link to post
Share on other sites
Yes ive just written a similar function to do that - was just hoping there was a more standard way of doing the same thing!

Thanks :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!