背景:
在编写跨平台的c++代码时,通常会遇到格式化函数不能同时兼容Windows平台和Linux平台的问题,如:sprintf函数,在msvc编译器下没有问题,但到了Linux平台下的编译器就不识别了。
问题:
字符串格式化的跨平台方案。
解决方案:
在支持c++11的情况下,可使用如下方案(直接上代码):
template<typename ... Args>
static std::string str_format(const std::string &format, Args ... args)
{
auto size_buf = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1;
std::unique_ptr<char[]> buf(new(std::nothrow) char[size_buf]);
if (!buf)
return std::string("");
std::snprintf(buf.get(), size_buf, format.c_str(), args ...);
return std::string(buf.get(), buf.get() + size_buf - 1);
}
int main(int argc, char *argv[])
{
std::string strFormat = str_format("%d %.2f 0x%x", 1, 2., 10);
std::cout << strFormat <&l