代码 :
#include <stdarg.h>
#include <string>
#include <iostream>
std::wstring string_format(const std::wstring &fmt, ...) {
int size = 100;
std::wstring str;
va_list ap;
while (1) {
str.resize(size);
va_start(ap, fmt);
int n = vsnwprintf((wchar_t *)str.c_str(), size, fmt.c_str(), ap);
va_end(ap);
if (n > -1 && n < size) {
str.resize(n);
return str;
}
if (n > -1) size = n + 1;
else size *= 2;
}
return str;
}
std::wstring printf_wrapper(std::wstring text, ...) {
using namespace std;
va_list args;
va_start(args, text);
wstring formatted_text = string_format(text, args);
va_end (args);
return formatted_text;
}
int main(int argc, char *argv[])
{
using namespace std;
wcout << printf_wrapper(L"example%d",1) << endl;
return 0;
}
它返回:example2293384
函数来自这里:https : //stackoverflow.com/a/8098080/393087 此代码的来源来自 vsnprintf 的文档:http ://www.tin.org/bin/man.cgi?section=3&topic= vsnprintf