Created
February 17, 2012 05:38
-
-
Save aont/1850964 to your computer and use it in GitHub Desktop.
sprintf returning std::string
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
| /* from http://www.ohfuji.name/?p=4 */ | |
| #include <cstdio> | |
| #include <cstdlib> | |
| #include <cstdarg> | |
| #include <vector> | |
| #include <string> | |
| #include <stdexcept> | |
| std::string str_printf(const char* const format, ...) | |
| { | |
| int bufsize = 1024; | |
| std::vector<char> buff(bufsize); | |
| va_list args; | |
| /// first try | |
| va_start(args, format); | |
| int vssize = vsnprintf( &buff[0], bufsize, format, args); | |
| va_end(args); | |
| /// if bufsize is sufficient, return | |
| if(vssize>=0 && vssize<bufsize) { | |
| buff.resize(vssize); | |
| return std::string(buff.begin(), buff.end()); | |
| } | |
| if(vssize<0) throw std::runtime_error(format); | |
| /// resize and retry | |
| buff.resize(vssize + 1); | |
| va_start(args, format); | |
| vssize = vsnprintf(&buff[0], vssize + 1, format, args); | |
| va_end(args); | |
| if(vssize<0) throw std::runtime_error(format); | |
| buff.resize(vssize); | |
| return std::string(buff.begin(), buff.end()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment