Unicode下CString和char *之間的互相轉換

來源:互聯網
上載者:User

 CString中儲存的字元的資料類型為wchar_t類型。

一、CString轉換為char *

(1)方法一:使用wcstombs()

#include <iostream>using namespace std;#include <atlstr.h>int main(){CString str = L"liuxijiao電腦網路";wchar_t *pWChar = str.GetBuffer(); //擷取str的寬字元用數組儲存str.ReleaseBuffer();int nLen = str.GetLength(); //擷取str的字元數char *pChar = new char[nLen * 2 + 1]; memset(pChar, 0, nLen * 2 + 1);int rtnVal = (int)wcstombs(pChar, pWChar, nLen * 2 + 1); //寬字元轉換為多位元組字元cout<<pChar<<endl;         delete[] pChar;return 0;}

輸出結果:

注意到結果沒有輸出“電腦網路”,那是因為wcstombs()不支援中文。

(2)方法二:使用WideCharToMultiByte();

#include <iostream>using namespace std;#include <atlstr.h>int main(){CString str = L"liuxijiao電腦網路";int n = str.GetLength(); //擷取str的字元數int len = WideCharToMultiByte(CP_ACP, 0, str, n, NULL, 0, NULL, NULL); //擷取寬位元組字元的大小,大小是按位元組計算的char *pChar = new char[len + 1]; //以位元組為單位WideCharToMultiByte(CP_ACP, 0, str, n, pChar, len, NULL, NULL); //寬位元組編碼轉換成多位元組編碼pChar[len + 1] = '\0'; //多位元組字元以'\0'結束cout<<pChar<<endl;         delete[] pChar;return 0;}

輸出結果:

二、char *轉換為CString

(1)方法一:使用_T()宏

CString str = _T("liuxijiao電腦網路");

(2)方法二:使用API的函數MultiByteToWideChar()

#include <iostream>using namespace std;#include <atlstr.h>#include <stdio.h>#include <string.h>int main(){//將char數群組轉換為wchar_t數組char *pChar = "liuxijiao電腦網路";int charLen = strlen(pChar); //計算pChar所指向的字串大小,以位元組為單位,一個漢字佔兩個位元組int len = MultiByteToWideChar(CP_ACP, 0, pChar, charLen, NULL, 0); //計算多位元組字元的大小,按字元計算wchar_t *pWChar = new wchar_t[len + 1]; //為寬位元組字元數申請空間,MultiByteToWideChar(CP_ACP, 0, pChar, charLen, pWChar, len); //多位元組編碼轉換成寬位元組編碼pWChar[len] = '\0';//將wchar_t數群組轉換為CStringCString str;str.Append(pWChar);delete[] pChar;delete[] pWChar;return 0;}

在str.Append(pWChar);這條語句處設斷點,調試運行,可查看到str的內容為"liuxijiao電腦網路"。

(三)方法三:使用A2T()、A2W()

char *pChar = "liuxijiao電腦網路";USES_CONVERSION;CString str = A2T(pChar);
char *pChar = "liuxijiao電腦網路";USES_CONVERSION;CString str = A2W(pChar);

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.