Here's a nice feature for C ++ sprintf. Streams can become ugly if you use them too much.
std::string string_format(const std::string &fmt, ...) { int n, size=100; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf(&str[0], size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) return str; if (n > -1) size = n + 1; else size *= 2; } }
In C ++ 11 and later versions of std :: string, the use of continuous storage is guaranteed, which ends with '\0'
, so it is legal to pass it to char *
using &str[0]
.
Erik Aronesty Dec 02 '11 at 9:11
source share