C++編程中屢屢要遇到寬窄字符轉換的問題,尤其是字符串中有中文,稍有不慎就會中文亂碼,程序運行出錯。
下面為char*、char[]與TCHAR*、TCHAR[]互轉的用法,不求花哨,只求好用!請參考~
char轉TCHAR
char轉TCHAR
1
2 3 4 5 6 7 |
char szWord[20] = "Hello World"; TCHAR tszWord[1024] = {0}; #ifdef UNICODE MultiByteToWideChar(CP_ACP, 0, szWord, -1, tszWord, 1024); #else strcpy(tszWord, szWord); #endif |
TCHAR轉char
char轉TCHAR
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn) { LPSTR pszOut = NULL; if (lpwszStrIn != NULL) { int nInputStrLen = wcslen(lpwszStrIn); // Double NULL Termination int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2; pszOut = new char[nOutputStrLen]; if (pszOut != NULL) { memset(pszOut, 0x00, nOutputStrLen); WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0); } } return pszOut; } |