C++11 格式化字符串format
template <typename ...Args>
static std::string format_string(const char* format, Args... args) {
char buffer[BUFSIZ] = {0};
size_t newlen = snprintf(buffer, BUFSIZ, format, args...);
if (newlen > BUFSIZ)
{
std::vector<char> newbuffer(newlen + 1);
snprintf(newbuffer.data(), newlen, format, args...);
return std::string(newbuffer.data());
}
return buffer;
}
template <typename ...Args>
static std::string format_string(const char* format, Args... args) {
char buffer[4096] = { 0 };
size_t newlen = vsnprintf(buffer, 4096, format, args...);
if (newlen > 4096)
{
std::vector<char> newbuffer(newlen + 1);
vsnprintf(newbuffer.data(), newlen, format, args...);
return std::string(newbuffer.data());
}
return buffer;
}
template <typename ...Args>
static std::string format_wstring(const wchar_t* format, Args... args) {
wchar_t buffer[4096] = { 0 };
int newlen = _vsnwprintf(buffer, 4096, format, args...);
if (newlen > 4096)
{
std::vector<wchar_t> newbuffer(newlen + 1);
_vsnwprintf(newbuffer.data(), newlen, format, args...);
return std::wstring(newbuffer.data());
}
return buffer;
}
用法:
std::string text = format_string("%.0f%%", 12.0f);
std::cout << text << std::endl;