char与TCHAR相互转换(拒绝中文乱码,好用!)

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, NULL000) + 2;
        pszOut = 
new char[nOutputStrLen];
        
if (pszOut != NULL)
        {
            memset(pszOut, 0x00, nOutputStrLen);
            WideCharToMultiByte(CP_ACP, 
0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 00);
        }
    }
    
return
 pszOut;
}
原文地址:https://www.cnblogs.com/MakeView660/p/9395800.html