Unicode下字串與整型等的格式轉換

來源:互聯網
上載者:User

一、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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.