0

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

Community
  • 1
  • 1
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • There's no guarantee that blasting characters into the character buffer that you get with `c_str()` will do anything meaningful. That's why it's marked `const`. Create a C-style array and blast characters into that, then copy them into the string. – Pete Becker Jan 16 '13 at 15:07

1 Answers1

3

You cannot "forward" varargs like that. So string_format needs to take a va_list as its 2nd argument, not ....

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680