Sign in to follow this  

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

This topic is 4520 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
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

This topic is 4520 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this