I wanted to place text formatted with a printf-type formatting string in a C++ string. I came up with the following method, which seems to work, but I haven't found anyone else admitting to using a similar technique, so I thought I would ask for reasons why I should not do this.
#include <stdio.h>
#include <stdarg.h>
#include <string>
void stringprintf(std::string &str, char const *fmt, ...) {
va_list ap;
va_start(ap, fmt);
size_t n = vsnprintf(NULL, 0, fmt, ap);
str.resize(n + 1, '\0');
char *pStr = (char *)(str.c_str());
(void)vsnprintf(pStr, str.capacity(), fmt, ap);
va_end(ap);
}
void dumpstring(std::string &str) {
printf("Object: %08X, buffer: %08X, size: %d, capacity: %d\ncontents: %s==\n",
&str, str.c_str(), str.size(), str.capacity(), str.c_str());
}
int main(int argc, char **argv) {
std::string str;
dumpstring(str);
stringprintf(str, "A test format. A number %d, a string %s!\n", 12345, "abcdefg");
printf("%s", str.c_str());
dumpstring(str);
return 0;
}