sprintf style function to tell you how big your buffer needs to be?
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?
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:
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
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
You can use this cheap hack:
char buf[SOME_BIG_NUMBER];
int l=_snprintf(buf,SOME_BIG_NUMBER,your array,your args);
return l;
char buf[SOME_BIG_NUMBER];
int l=_snprintf(buf,SOME_BIG_NUMBER,your array,your args);
return l;
Quote:Original post by ToohrVyk
In C, you can use snprintf with size = 0.
In C++, just don't.
Wouldn't snprintf return 0?
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).
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.
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;
}
#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;
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement