On Fri, Apr 03, 2015 at 09:48:22PM -0500, Greg London wrote: > Cool! 15 years of perl and I never used /e > > I got the regexp to convert the first file > and discovered that sprintf is way more inconvenient > than I remember. It doesn't return the string, > it returns pass/fail. And it operates on char* ? > > This may have been why I used boost::format. > > Anyone know of a c++ self contained function that takes > a format string and returns the result string > rather than using char*'s and returning the value in > a char*?
I ran into this problem with C code some time ago. sprintf and friends do not return the string because that would require them to allocate the memory for the string, which raises difficult questions of ownership and memory management. Instead, you are expected to pre-allocate the memory and pass it in as a char * argument so sprintf can write to it. But how do you know how big to make the string? The basic idea is to call snprintf with a zero length value and it will tell you how big the string should be so you can make a second call with the correct length. It works, but is annoying. I suspect most programmers write utility code to abstract this stuff away. Here's the code I wrote back then to solve the problem, it's extracted from my util library so there are references to other util or application functions but they are pretty obvious. Note that you are expected to deallocate the string after use. char * xvstrfmt (const char *fmt, va_list args) { int size = 0; char *str = NULL; int n; for (;;) { n = vsnprintf (str, size, fmt, args); if (n == -1) { fatal_sys ("vsnprintf"); } else if (n < size) { return str; } else { size = n + 1; str = xrealloc (str, size); } } return NULL; } char * xstrfmt (const char *fmt, ...) { va_list args; char *str; va_start (args, fmt); str = xvstrfmt (fmt, args); va_end (args); return str; } -Gyepi _______________________________________________ Boston-pm mailing list Boston-pm@mail.pm.org http://mail.pm.org/mailman/listinfo/boston-pm