Wednesday, April 8, 2009

CString in MFC

Localization in a VC++ project has been one of the things that I have been working on recently. I haven't come across much issues. But one thing which really surprised me was the MakeUpper() function in CString.

CString is supposed to handle UNICODE character set. So I was expecting MakeUpper() to generally convert the string in unicode to its respective uppercase characters..Alas!!

If you tend to have accented characters in your string then MakeUpper() doesnt work as expected. So the fix??

I did quite a number of searches and found out that many have faced this issue and found out the fix too. Make use of setlocale() function. This function sets the locale to the locale that we specify. For instance, we re working on hungarian characters and we intend to convert the french characters to uppercase, then we need to set the locale to french code page first and then call the MakeUpper() of CString.

The fix is as follows:

_tsetlocale(LC_CTYPE, L"French_Canada.1252");
CString temp(csUserName);
csUserName.MakeUpper();


There is a catch here too. If the code page is UTF-7 or UTF-8, then setlocale() fails.

MSDN link for setlocale()

No comments: