Thursday, August 30, 2007

C++ String-Utils

Ever had the problem of wanting to use (s)printf to format a string into an STL/StdC++ std::string instance? The only thing STL says is, "use strstream", which I don't agree with ... (s)printf is easier to use once you get used to the %s stuff, and often cleaner to read. Thus, I wrote my own method ... maybe I just used to much String.format() in Java ;-)



#include <string>

std::string formatString(const char* format, ...); 

#endif /*STRINGUTILS_HH_*/

#include "StringUtils.hh"
#include "BufferUtils.hh"

#include <stdarg.h>
using std::string;

 No need to be afraid about memory leaks, segfaults 
   or buffer overflows (hopefully)
 - the 2kB buffer is freed on return (destructor)
 - the std::string is instantiated before the 
   buffer is freed, and returned on the stack
 - vsnprintf checks the buffer length, and the last char 
   is ensured to be a '\0'
std::string formatString(const char* format, ...) {
 Buffer buffer(2048);
 va_list vl;
 va_start(vl, format);
 vsnprintf(buffer, buffer.bufferSize(), format, vl);
 buffer[buffer.bufferSize()-1] =0;
 return string(buffer);

No comments: