#include <memory>
#include <string>
#include <stdexcept>
template<typename ... Args>
std::string string_format( const std::string& format, Args ... args )
{
size_t size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
std::unique_ptr<char[]> buf( new char[ size ] );
snprintf( buf.get(), size, format.c_str(), args ... );
return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}
// Testing
#include <iostream>
int main() {
//test the function here
std::cout << string_format("%d", 202412);
//<test>
return 0;
}
I2luY2x1ZGUgPG1lbW9yeT4KI2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPHN0ZGV4Y2VwdD4KCnRlbXBsYXRlPHR5cGVuYW1lIC4uLiBBcmdzPgpzdGQ6OnN0cmluZyBzdHJpbmdfZm9ybWF0KCBjb25zdCBzdGQ6OnN0cmluZyYgZm9ybWF0LCBBcmdzIC4uLiBhcmdzICkKewogICAgc2l6ZV90IHNpemUgPSBzbnByaW50ZiggbnVsbHB0ciwgMCwgZm9ybWF0LmNfc3RyKCksIGFyZ3MgLi4uICkgKyAxOyAvLyBFeHRyYSBzcGFjZSBmb3IgJ1wwJwogICAgaWYoIHNpemUgPD0gMCApeyB0aHJvdyBzdGQ6OnJ1bnRpbWVfZXJyb3IoICJFcnJvciBkdXJpbmcgZm9ybWF0dGluZy4iICk7IH0KICAgIHN0ZDo6dW5pcXVlX3B0cjxjaGFyW10+IGJ1ZiggbmV3IGNoYXJbIHNpemUgXSApOyAKICAgIHNucHJpbnRmKCBidWYuZ2V0KCksIHNpemUsIGZvcm1hdC5jX3N0cigpLCBhcmdzIC4uLiApOwogICAgcmV0dXJuIHN0ZDo6c3RyaW5nKCBidWYuZ2V0KCksIGJ1Zi5nZXQoKSArIHNpemUgLSAxICk7IC8vIFdlIGRvbid0IHdhbnQgdGhlICdcMCcgaW5zaWRlCn0KCgovLyBUZXN0aW5nCiNpbmNsdWRlIDxpb3N0cmVhbT4KCmludCBtYWluKCkgewoJLy90ZXN0IHRoZSBmdW5jdGlvbiBoZXJlCglzdGQ6OmNvdXQgPDwgc3RyaW5nX2Zvcm1hdCgiJWQiLCAyMDI0MTIpOwoJLy88dGVzdD4KCXJldHVybiAwOwp9