一、int等 轉 CString
int i;
CString msg= _T("");
msg.Format( _T("%d"), i);
同理對於long、double、char等適用.注意:必須適用_T()函數。
二、CString 轉 int
CString msg = _T("123");
int i = _ttoi( msg );
三、CString 轉 long
CString msg = _T("123");
long i = _tcstol( msg , 0 , 10 );
使用_tcstoul()或者_tcstol(),它們都能把字串轉化成任意進位的長整數(如二進位、八進位、十進位或十六進位),不同點在於前者轉化後的資料是無符號的(unsigned),而後者相反。
四、CString 轉 double
CString msg = _T("123");
double i = _tcstod( msg , 0 );
其他,
// 把寬字元轉化為ANSI字串
WideCharToMultiByte( CP_ACP, 0, lpcwStr, -1, lpStr, sizeof(lpStr), NULL, NULL );
// 把ANSI字串轉化為寬字元
MultiByteToWideChar( CP_ACP, 0, lpcStr, -1, lpwStr, sizeof(lpwStr) );
為支援Unicode做準備,除個別必須使用 char 或 char* 的地方外,
其它地方請依照如下標準:
1.字串類型盡量用CString
2.字元類型使用 TCHAR
3.字串數組用 TCHAR[]
4.字串指標用 TCHAR*
5.常量字串指標用 const TCHAR*
6.字串常量和字元常量加宏 _T
特別的:
1>CString::Format(_T("..."),...)//要加_T
2>LPTSTR 等等被多次嵌套定義過的宏盡量少用,用基礎類型 const TCHAR*(或TCHAR*)替代;
3>為TCHAR*類型指標分配 N-1 個字元的空間: TCHAR* pbuffer = new TCHAR[ N*sizeof(TCHAR) ];
常用字串函數,須使用支援Unicode/Ansi的宏函數替換前者:
Ansi字串函數 Unicode/Ansi宏函數 功能說明
strcpy _tcscpy 字串拷貝
strcat _tcscat 字串串連
strlen _tcslen 求字串長度
strcmp _tcscmp 字串比較
atof _tcstod (注) 字串轉換為double
atoi _ttoi 字串轉換為int
註:上表中 _tcstod 和 atof用法不同,不能直接替換。
LPCTSTR 使用 UELPCTSTR 代替
std::string 使用 UeStdString 代替
這個需要加ShareHeader.h標頭檔
#ifdef UNICODE
typedef std::wstring UeStdString;
#define UELPCSTR LPCWSTR
#else
typedef std::string UeStdString;
#define UELPCSTR LPCTSTR
#endif