天下苦stl字符串格式化久矣!
template<typename ... Args>
static std::string FormatString(const std::string& format, Args ... args)
{
auto size = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args ...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
template<typename ... Args>
static std::wstring FormatString(const std::wstring& format, Args ... args)
{
auto size = std::swprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr<wchar_t[]> buf(new wchar_t[size]);
std::swprintf(buf.get(), size, format.c_str(), args ...);
return std::wstring(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
#define TYFORMAT(fmt,...) FormatString(fmt,__VA_ARGS__)
int main()
{
{
std::string str;
str = TYFORMAT("%d %s", 12, "hello wrold");
printf("%s\n", str.c_str());
}
{
std::wstring str;
str = TYFORMAT(L"%d %s", 12, L"hello wrold");
printf("%ws\n", str.c_str());
}
getchar();
return 0;
}
结果: