2010年9月28日 星期二

CString 與常用型態互轉

因為 C++ 的型態太多了,沒有常用真的會忘記,記下來,
但由於真的太多了,並不是很完整,之後有碰到會再補上來。

● 數字類

CString to int


CString strSource;
int n = _ttoi(strSource);


CString to LONG


CString strSource;
int n = _ttol(strSource);


CString to double


CString strSource;
double dbl = _tstof((LPTSTR)(LPCTSTR)strSource);

// 或是有些平台上沒有 _tstof 就要先轉成 ansi 再用 atof 來轉

int nIndexTemp = WideCharToMultiByte(CP_ACP, 0, strSource, -1, NULL, 0, NULL, NULL);
char *pAnsi = (char*)malloc(nIndexTemp + 1);
ZeroMemory(pAnsi, nIndexTemp + 1);
WideCharToMultiByte(CP_ACP, 0, strSource, -1, pAnsi, nIndexTemp, NULL, NULL);
double dbl = atof(pAnsi);
free(pAnsi);


CString to LONGLONG


CString strSource;
LONGLONG ll = _ttoi64(strSource);


LONGLONG to CString


CString strData;
strData.format(_T("%I64d"), ll);



● 各類字串

CString to BYTE*


CString strSource;
BYTE* pbt = (BYTE*)(T2A((LPTSTR)(LPCTSTR)strSource);
// 或有特殊需求可使用 strdup 複製一份,但要記得自己 free 掉
(BYTE*)strdup(T2A((LPTSTR)(LPCTSTR) strContentKey));


CString to char*


CString strSource;
char* psz = T2A((LPTSTR)(LPCTSTR)strSource);


CString to unsigned char*


CString str;
unsigned char *ptr2 = (unsigned char*)str.GetBuffer(0);


BYTE* to CString


BYTE* pBuf;
CString str = W2T((LPWSTR)pBuf);


CString to TCHAR*


CString strSource;
TCHAR *ptc = (TCHAR*)T2W((LPTSTR)(LPCTSTR)strSource);
// 或
TCHAR *ptc = (LPTSTR)(LPCTSTR)strSource;


CString to CComBSTR


CString strSource;
CComBSTR bstrSS(strSource);


BSTR to CString


BSTR bstrText;
CString strData;
strData = bstrText;


CString to LPWSTR


CString strSource;
LPWSTR lstr = (LPWSTR)(LPCTSTR)strSource;

2 則留言: