http://blog.sina.com.cn/s/blog_4d1865f00100o26b.html
1.頭文件中要定義宏;
#define UNICODE
#define _UNICODE
2.char轉(zhuǎn)換成wchar
const char *pFilePathName = "c:\\aa.dll";
int nLen = strlen(pFilePathName) + 1;
int nwLen = MultiByteToWideChar(CP_ACP, 0, pFilePathName, nLen, NULL, 0);
TCHAR lpszFile[256];
MultiByteToWideChar(CP_ACP, 0, pFilePathName, nLen, lpszFile, nwLen);
3.wchar轉(zhuǎn)換成char
char *pFilePathName;
TCHAR lpszFile[256];
_tcscpy(lpszFile, _T("c:\\aa.dll"));
int nLen = wcslen(wstr)+1;
WideCharToMultiByte(CP_ACP, 0, lpszFile, nLen, pFilePathName, 2*nLen, NULL, NULL);
4.char*和CString轉(zhuǎn)換
CString 是一種很特殊的 C++ 對象,它里面包含了三個值:一個指向某個數(shù)據(jù)緩沖區(qū)的指針、一個是該緩沖中有效的字符記數(shù)(它是不可存取的,是位于 CString 地址之下的一個隱藏區(qū)域)以及一個緩沖區(qū)長度。有效字符數(shù)的大小可以是從0到該緩沖最大長度值減1之間的任何數(shù)(因?yàn)樽址Y(jié)尾有一個NULL字符)。字符記數(shù)和緩沖區(qū)長度被巧妙隱藏。
(1) char*轉(zhuǎn)換成CString
若將char*轉(zhuǎn)換成CString,除了直接賦值外,還可使用CString::Format進(jìn)行。例如:
char chArray[] = "Char test";
TCHAR * p = _T("Char test");( 或LPTSTR p = _T("Char test");)
CString theString = chArray;
theString.Format(_T("%s"), chArray);
theString = p;
(2) CString轉(zhuǎn)換成char*
若將CString類轉(zhuǎn)換成char*(LPSTR)類型,常常使用下列三種方法:
方法一,使用強(qiáng)制轉(zhuǎn)換。例如:
CString theString( (_T("Char test "));
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
方法二,使用strcpy。例如:
CString theString( (_T("Char test "));
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);
需要說明的是,strcpy(或可移值的_tcscpy)的第二個參數(shù)是 const wchar_t* (Unicode)或const char* (ANSI),系統(tǒng)編譯器將會自動對其進(jìn)行轉(zhuǎn)換。
方法三,使用CString::GetBuffer。
如果你需要修改 CString 中的內(nèi)容,它有一個特殊的方法可以使用,那就是 GetBuffer,它的作用是返回一個可寫的緩沖指針。如果你只是打算修改字符或者截短字符串,例如:
CString s(_T("Char test "));
LPTSTR p = s.GetBuffer();
LPTSTR dot = strchr(p, ''.'');
// 在這里添加使用p的代碼
if(p != NULL)
*p = _T('\0');
s.ReleaseBuffer(); // 使用完后及時釋放,以便能使用其它的CString成員函數(shù)
在 GetBuffer 和 ReleaseBuffer 之間這個范圍,一定不能使用你要操作的這個緩沖的 CString 對象的任何方法。因?yàn)?ReleaseBuffer 被調(diào)用之前,該 CString 對象的完整性得不到保障。
5.CString 轉(zhuǎn)為 int
將字符轉(zhuǎn)換為整數(shù),可以使用atoi、_atoi64或atol。
CString aaa = "16" ;
int int_chage = atoi(aaa) ;
得到 int_chage = 16
int atoi(const char *nptr);
long atol(const char *nptr);
long long atoll(const char *nptr);
long long atoq(const char *nptr);
6.int 轉(zhuǎn)為 CString
而將數(shù)字轉(zhuǎn)換為CString變量,可以使用CString的Format函數(shù)。如
CString s;
int i = 64;
s.Format("%d", i)
itoa是廣泛應(yīng)用的非標(biāo)準(zhǔn)C語言擴(kuò)展函數(shù)。由于它不是標(biāo)準(zhǔn)C語言函數(shù),所以不能在所有的編譯器中使
用。但是,大多數(shù)的編譯器(如Windows上的)通常在<stdlib.h>頭文件中包含這個函數(shù)。在<stdlib.h>中與之有相反功能的函數(shù)是atoi。功能:把一整數(shù)轉(zhuǎn)換為字符串。