Using wsprintf to convert int to wchar_t *

I am trying to get wchar_t* in int format as a parameter. I walked a lot, but I was only more embarrassed. 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; }; 

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

(I must clarify that portability is more important than security here, so I would like to know a solution that uses this family of functions instead of the more secure extensions associated with the manufacturers.)

+4
source share
3 answers

wsprintf() is a Windows-specific function, it is not available for Unix. (I would not be surprised if there was an error in its implementation ...) What you want to achieve can be done in a more portable way (I tried this slightly modified code fragment and 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] 
+5
source

wsprintf() is one of the hybrid functions of Microsoft. It has a different signature depending on whether _UNICODE defined during _UNICODE . (What happens under the hood is #ifdef , which replaces wsprintf with wsprintfA or wsprintfW based on the nonexistence or existence of this character.)

If _UNICODE specified, it expects the buffer to be wchar_t[] .

If _UNICODE not defined (usually the default), it expects the buffer to be char[] . This is what happens here. If you have warnings, you will probably see a warning about incompatible pointer types. Trash because the 8-bit ascii it stores in buf is interpreted as Unicode on wprintf() .

+2
source

It seems to me that you are using the wrong format specifier for your output. I suspect you will want

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

% ls looks like an invalid combination of qualifiers - l for the prefix of size "long int" in the specifier of type s "string". The documentation I found on wprintf indicates that it treats the type specifier s as an indication of a wide character string (at least for MS Visual Studio).

+1
source

All Articles