c++wchar

Can't print char* in WCHAR* with swprintf


I have that function that work (I just have to turn wstring to WHAR* at the end):

wstring stringtowstring(string str)
{
    WCHAR ch[256];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)ch, 256);

    return wstring(ch);
}

But I would like to know why that doesn't:

WCHAR tmp[256];
swprintf(tmp, L"%s", "test");

Solution

  • Assuming Visual Studio in the context, this is a documented non-standard behavior of swprintf.

    Character and string arguments that are specified by using c and s are interpreted as char and char* by printf family functions, or as wchar_t and wchar_t* by wprintf family functions. Character and string arguments that are specified by using C and S are interpreted as wchar_t and wchar_t* by printf family functions, or as char and char* by wprintf family functions. This behavior is Microsoft-specific.

    Microsoft-specific: The Z type character, and the behavior of the c, C, s, and S type characters when they are used with the printf and wprintf functions, are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters and strings, in all formatting functions.