C++中实现格式化字符串函数std::string string_format(const char *format, …)
参考连接
本文实现方法参考以下连接:
参考连接:https://blog.csdn.net/pop1210/article/details/51729355
但是连接中代码编译存在问题,代码也有明显的错误,
不排除在某些特定平台可以编译,但是在linux平台编译是有问题的,
对代码进行了修改,测试编译可通过。
修正后的代码
#include <stdio.h>
#include <stdarg.h> // va_start va_end
#include <string>
std::string string_format(const char *format, ...)
{
va_list args;
va_start(args, format);
int count = vsnprintf(NULL, 0, format, args);
va_end(args);
va_start(args, format);
char *buff = (char *)malloc((count + 1) * sizeof(char));
vsnprintf(buff, (count + 1), format, args);
va_end(args);
std::string str(buff, count);
free(buff);
return str;
}
int main(int argn, char **argv)
{
std::string output;
for (int i = 0; i < 100; i++)
{
output += string_format("[%d]", output.size());
printf("%s => [%d %zu]\n", output.c_str(), i, output.size());
}
return 0;
}
修改内容
- vsnprintf函数返回的count长度是不带‘\0’的长度,所有开辟的空间也要比count+1,写入长度也要count+1
- malloc开辟类型为sizeof(wchar_t),这个开辟的可以4倍空间。
总结
网上的代码用前一定要测试一下