Using wsprintf to convert int to wchar_t*

Deadly 提交于 2019-12-01 06:43:49

wsprintf() is a Windows-specific function, it's unavailable on Unixes. (I wouldn't be surprised if its implementation contained a bug...) 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]

wsprintf() is one of Microsoft's hybrid functions. It has a different signature depending on whether or not _UNICODE is defined during preprocessing. (What's happening under the hood, is there's an #ifdef that replaces wsprintf with wsprintfA or wsprintfW based on the nonexistence or existence of that symbol.)

If _UNICODE is defined, it expects the buffer to be of wchar_t[].

If _UNICODE is not defined (usually the default), it expects the buffer to be char[]. That's what's happening here. If you had warnings on, it would probably show a warning about incompatible pointer types. The garbage is because the 8-bit ascii that it's storing in buf is being interpreted as Unicode by wprintf().

It appears to me that you're using an incorrect format specifier for your output. I would suspect you would want

wprintf(L"[%s]\n", buf);

%ls looks like an invalid combination of specifiers - l for a "long int" size prefix on the s "string" type specifier. Documentation I've found on wprintf indicates that it treats the 's' type specifier as pointing to a wide character string (at least for MS Visual Studio).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!