Search code examples
cwchar-t

Using wsprintf to convert int to wchar_t*


I'm trying to get a wchar_t* formatted with an int as a parameter. I've Googled a lot but I've only ended up more confused. So, consider this code:

int main(int argc, char** argv) {

   wchar_t buf[16];
   wsprintf(buf, L"%d", 5);
   wprintf(L"[%ls]\n", buf);

   system("pause");
   return 0;

};

Having assumed that wchar_t, wsprintf and wprintf are the wide character equivalents of char, sprintf and printf respectively, I expected the above to print [5], but it prints garbage between [ and ]. What is the correct way to achieve the desired result? And what am I misunderstanding here?

(I should clarify that portability is more important than security here, so I'd like to know a solution that uses this family of functions instead of safer vendor-specific extensions.)


Solution

  • wsprintf() is a Windows-specific function, it's unavailable on Unixes. What you want to achieve can be done in a more portable way (I have tried this slightly modified code snippet and it worked as expected):

    #include <wchar.h>
    #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        wchar_t buf[16];
        swprintf(buf, sizeof(buf) / sizeof(*buf), L"%d", 5);
        wprintf(L"[%ls]\n", buf);
    
        return 0;
    }
    

    Output:

    [5]