Created
December 21, 2011 08:13
-
-
Save piti118/1505174 to your computer and use it in GitHub Desktop.
C++ missing std::string printf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdarg> | |
#include <string> | |
//missing string printf | |
//this is safe and convenient but not exactly efficient | |
inline std::string format(const char* fmt, ...){ | |
int size = 512; | |
char* buffer = 0; | |
buffer = new char[size]; | |
va_list vl; | |
va_start(vl,fmt); | |
int nsize = vsnprintf(buffer,size,fmt,vl); | |
if(size<=nsize){//fail delete buffer and try again | |
delete buffer; buffer = 0; | |
buffer = new char[nsize+1];//+1 for /0 | |
nsize = vsnprintf(buffer,size,fmt,vl); | |
} | |
std::string ret(buffer); | |
va_end(vl); | |
delete buffer; | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment