Sunday, 6 April 2014

Converting a WORD to LPCWSTR (LPCSTR)

The easiest way to do this is to use the sprintf family of functions.

int sprintf (char * szBuffer, const char * szFormat, ...);

If you are coming from a C background, this will naturally remind you of the printf function:

int printf (const char * szFormat, ...);

printf doesn't "work" in a Windows program, because Windows does not have a concept of standard input and output. sprintf differs only in that the first argument is the destination buffer. An example to convert a WORD to LPC(W)STR is as follows:

TCHAR buffer[5];
s(w)printf(buffer, "%i", 15);


Now buffer will contain the string "15". These functions are so common, the Windows API has versions of them as well:

(Version: ASCII, Unicode, generic)
Standard: sprintf, swprintf, _stprintf
Windows: wsprintfA, wsprintfW, wsprintf


Of course, the usual caveats apply when using the printf family - buffer size, proper format string, etc. Naturaly, more secure versions of the functions are available, for example sprintf_s.

No comments:

Post a Comment