Skip to content

Instantly share code, notes, and snippets.

@egtra
Created December 18, 2013 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egtra/8023656 to your computer and use it in GitHub Desktop.
Save egtra/8023656 to your computer and use it in GitHub Desktop.
std::stringを返すsprintf/vsprintfラッパー
#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