About Mikazo Tech Blog

My name is Mike, and this blog is my way of saving people time. If someone has a specific problem that I've encountered before, hopefully these posts will save them the extraneous Googling I had to go through to solve the same problem. Also, when I have something to say about technology today, I will post my thoughts here. If this blog has helped you out, even a little bit, vote on the poll below, or let me know by sending me an email. I'm always open to exchanging links with other blogs or websites that share a similar interest.

Friday, March 13, 2009

Printing Unicode C-Style Strings with Variables in C++ MessageBox

This drove me nuts for hours. The MessageBox function wants wide-character strings and I wanted to put variables in my strings, not just L"" constant strings. I had already been using the Unicode character set and didn't want to change a million other things in my code, so after much toiling, I've found the following code snippet to work:


int random = 42;
char message[128];
sprintf(message, "My random number: %d\n", random);
wchar_t mess[128];
mbstowcs(mess, message, 512);
MessageBox(hWnd, mess, L"Information", MB_OK);


The 512 value in mbstowcs() should be WCHAR_MAX_LENGTH but I was too lazy to find which header contains that, so I Googled and found a random value. It seems to work for me.

0 comments:

Donate to Mikazo Tech Blog