Reputation: 29407
code :
#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;
}
and it returns : example2293384
the function is from here: https://stackoverflow.com/a/8098080/393087 origin of this code is from the documentation of vsnprintf: http://www.tin.org/bin/man.cgi?section=3&topic=vsnprintf
Upvotes: 0
Views: 181
Reputation: 272752
You cannot "forward" varargs like that. So string_format
needs to take a va_list
as its 2nd argument, not ...
.
Upvotes: 3