#include <stdio.h>
#include <stdarg.h>
void formatString(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
// Determine the size of the formatted string
int size = vsnprintf(NULL, 0, fmt, args);
// Allocate memory for the formatted string
char* buffer = malloc((size + 1) * sizeof(char));
// Format the string
vsprintf(buffer, fmt, args);
// Print the formatted string
printf("%s\n", buffer);
// Cleanup
free(buffer);
va_end(args);
}
int main()
{
formatString("Hello, %s! Today is %d-%d-%d.", "John", 2023, 5, 15);
return 0;
}
这种方法比较灵活,目前vsprintf可能会出现不安全的报错,如果需要关闭,可以在vs的工程-属性-C/C++->预处理器->,在预处理器定义里添加_CRT_SECURE_NO_WARNINGS