Alex Rivera | Logout

Quick formatted strings in C++

Asked 2011-04-16T12:51:41.040
19

Is there a quick, easy way of getting sprintf-like formatting when constructing a std::string? Something like...

std::string foo("A number (%d) and a character (%c).\n", 18, 'a');
Edit
Report

1 Answer

1

How about this one, it uses printf directly:

#include <stdio.h> 
#include <stdarg.h> 

std::string format(const char *fmt, ...) 
{ 
    va_list ap; 
    va_start(ap, fmt); 

    const size_t SIZE = 512; 
    char buffer[SIZE] = { 0 }; 
    vsnprintf(buffer, SIZE, fmt, ap); 

    va_end(ap); 

    return std::string(buffer); 
} 
answered 2011-04-16T14:03:24.250

Your Answer