Created
December 18, 2013 14:56
-
-
Save egtra/8023656 to your computer and use it in GitHub Desktop.
std::stringを返すsprintf/vsprintfラッパー
This file contains 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 <iostream> | |
#include <string> | |
#include <cstdarg> | |
#include <stdio.h> | |
std::string strvprintf(const char* format, std::va_list arg) | |
{ | |
std::string ret; | |
ret.resize(32); // この値は根拠なし。もう少し大きくても良いかもしれない。 | |
auto n = static_cast<std::size_t>(vsnprintf(&ret[0], ret.size(), format, arg)); | |
#if defined _MSC_VER | |
if (n == static_cast<std::size_t>(-1)) | |
{ | |
n = _vscprintf(format, arg) + 1; | |
#else | |
if (n > ret.size()) | |
{ | |
#endif | |
ret.resize(n + 1); | |
n = vsnprintf(&ret[0], ret.size(), format, arg); | |
} | |
ret.resize(n); | |
return ret; | |
} | |
std::string strprintf(const char* format, ...) | |
{ | |
std::va_list arg; | |
va_start(arg, format); | |
auto ret = strvprintf(format, arg); | |
va_end(arg); | |
return ret; | |
} | |
int main() | |
{ | |
std::cout << strprintf("%x", 0xffff) << std::endl; | |
std::cout << strprintf("%.3e", 12.3456) << std::endl; | |
std::cout << strprintf("%s\n%s", | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ", | |
"abcdefghijklmnopqrstuvwxyz") << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment