C++ TCHAR* 與char* 互轉


C++ TCHAR* 與char* 互轉

在MSDN中有這么一段:

Note: The ANSI code pages can be different on different computers, or can be changed for a single computer, leading to data corruption. For the most consistent results, applications should use Unicode, such as UTF-8 (code page 65001) or UTF-16, instead of a specific code page, unless legacy standards or data formats prevent the use of Unicode. If use of Unicode is not possible, applications should tag the data stream with the appropriate encoding name when protocols allow it. HTML, XML, and HTTP files allow tagging, but text files do not.

大概意思就是說ANSI頁碼的文件可能會根據不同的計算機而改變,建議使用unicode(UTF-8或UTF-16)的編碼

而VS默認就使用unicode編碼

ANSI:char, string …

UNICODE: TCHAR, wchar_t …

MSDN里給我們提花了兩個函數

MultiByteToWideChar

int MultiByteToWideChar(

UINT CodePage,

DWORD dwFlags,

LPCSTR lpMultiByteStr,

int cbMultiByte,

LPWSTR lpWideCharStr,

int cchWideChar

);

WideCharToMultiByte:

int WideCharToMultiByte(

UINT CodePage,

DWORD dwFlags, 

LPCWSTR lpWideCharStr,

int cchWideChar,

LPSTR lpMultiByteStr, 

int cbMultiByte,

LPCSTR lpDefaultChar,

LPBOOL lpUsedDefaultChar

);

互轉的實現:

char* StrUtils::TCHAR2char( const TCHAR* STR )

{

//返回字符串的長度

int size = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, FALSE);

//申請一個多字節的字符串變量

char* str = new char[sizeof(char) * size];

//將STR轉成str

WideCharToMultiByte(CP_ACP, 0, STR, -1, str, size, NULL, FALSE);

return str;

}

TCHAR* StrUtils::char2TCAHR( const char* str )

{

int size = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);

TCHAR* retStr = new TCHAR[size * sizeof(TCHAR)];

MultiByteToWideChar(CP_ACP, 0, str, -1, retStr, size);

return retStr;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM