Wchar, tchar, and their conversion functions in windows are annoying! However, there is no way to make a summary after the abuse, write down the learned things for future use.
Character encoding knowledge can be obtained from the Wiki, UTF-16 is Unicode, to ANSI is usually a byte of English characters, in the conversion of the mark is cp_acp: codepageansicodepage
1. A simple widechar string that does not contain Chinese characters is converted to a common char.
CString str("2012 0625");int nYear = 1, nMonth = 1, nDate = 1;swscanf(str.GetBuffer(), _T("%d %d"), &nYear, &nMonth);str.ReleaseBuffer();char charstring[1024];ZeroMemory(charstring,sizeof(charstring));WCHAR *wcharstring=str.GetBuffer();WideCharToMultiByte(CP_ACP,NULL,wcharstring,-1,charstring,1024,NULL,NULL);MultiByteToWideChar(CP_ACP,NULL,charstring,-1,wcharstring,1024);str.ReleaseBuffer();sscanf(charstring, ("%d %d"), &nYear, &nMonth);
2. when using multibytetowidechar, pay attention to it because we do not know how long the transfer length is. We need to first pass the output length to 0, this function returns the length in widechar units that will be input for conversion. Then, the memory is dynamically opened based on the returned value to store the output data. Call this function again and pass in the correct output length, to ensure that there is no character buffer issue.
char ansichar[] = "ansistring";TCHAR *pUtf16 = 0;TCHAR myTest[64] = {0};int k = MultiByteToWideChar(CP_ACP,0,ansichar,-1,pUtf16,0);pUtf16 = new TCHAR[k];MultiByteToWideChar(CP_ACP,0,ansichar,-1,pUtf16,k);
Note: The allocated space does not need to be allocated with k + 1, because this function has included \ 0 as the number of strings.