syntax-highlighter

Tuesday, September 18, 2012

Simple printf style formatting of std::string

Nothing special here but a quick snippet that allows an std::string to be formatted similar to printf, which I prefer.  Not a safe function by any means, but great for debugging and log files. I must have looked up the C variable argument list code dozens of times over the years.  May not work under Visual C++ if Microsoft hasn't yet come to terms with vsprintf() actually being a part of the C standard library.


#include<string>
#include<cstdio>
#include<cstdarg>

#define STR_FORMAT_BUFFER_SIZE 2048

std::string str_format( const char *fmt, ... ){
 char buffer[STR_FORMAT_BUFFER_SIZE];
 va_list arg;
 va_start( arg, fmt );
 vsprintf( buffer, fmt, arg );
 va_end(arg);
 return std::string(buffer);
}

No comments: