Search code examples
cstringwindowswidestring

Converting from int to wide character string using sprintf_s


My goal is to convert an int to a wide character string and prefix it with another wide string. My current solution is this:

#define bufsize 20
char buffer[bufsize];
sprintf_s(buffer,bufsize,"%s%d", "my prefix", 42);
wchar_t wbuffer[bufsize];
mbstowcs_s(NULL, wbuffer, buffer, bufsize);

I incorrectly expected that the following would work:

#define bufsize 20
wchar_t buffer[bufsize];
swprintf_s(buffer,bufsize,"%s%d",L"my prefix",  42);

Is there a more succinct version of my solution that works? It seems wrong that I have to do the int to char[] conversion and then convert to wchar_t[]. Why can't I just convert from int to wchar_t*?


Solution

  • You need the L prefix for the format string

    swprintf_s(buffer, bufsize, L"%s%d", L"my prefix",  42);
    

    The parameters can however be normal string, but you need to use %S in MSVC and %ls in standard C

    swprintf_s(buffer, bufsize, L"%S%d", "my prefix",  42);
    

    Note that macros typically have ALL_CAPS names to differentiate them from variables