http://blog.sina.com.cn/s/blog_4d1865f00100o26b.html
1.頭文件中要定義宏;
#define UNICODE
#define _UNICODE
2.char轉換成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轉換成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轉換
CString 是一種很特殊的 C++ 對象,它里面包含了三個值:一個指向某個數據緩沖區的指針、一個是該緩沖中有效的字符記數(它是不可存取的,是位于 CString 地址之下的一個隱藏區域)以及一個緩沖區長度。有效字符數的大小可以是從0到該緩沖最大長度值減1之間的任何數(因為字符串結尾有一個NULL字符)。字符記數和緩沖區長度被巧妙隱藏。
(1) char*轉換成CString
若將char*轉換成CString,除了直接賦值外,還可使用CString::Format進行。例如:
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轉換成char*
若將CString類轉換成char*(LPSTR)類型,常常使用下列三種方法:
方法一,使用強制轉換。例如:
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)的第二個參數是 const wchar_t* (Unicode)或const char* (ANSI),系統編譯器將會自動對其進行轉換。
方法三,使用CString::GetBuffer。
如果你需要修改 CString 中的內容,它有一個特殊的方法可以使用,那就是 GetBuffer,它的作用是返回一個可寫的緩沖指針。如果你只是打算修改字符或者截短字符串,例如:
CString s(_T("Char test "));
LPTSTR p = s.GetBuffer();
LPTSTR dot = strchr(p, ''.'');
// 在這里添加使用p的代碼
if(p != NULL)
*p = _T('\0');
s.ReleaseBuffer(); // 使用完后及時釋放,以便能使用其它的CString成員函數
在 GetBuffer 和 ReleaseBuffer 之間這個范圍,一定不能使用你要操作的這個緩沖的 CString 對象的任何方法。因為 ReleaseBuffer 被調用之前,該 CString 對象的完整性得不到保障。
5.CString 轉為 int
將字符轉換為整數,可以使用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 轉為 CString
而將數字轉換為CString變量,可以使用CString的Format函數。如
CString s;
int i = 64;
s.Format("%d", i)
itoa是廣泛應用的非標準C語言擴展函數。由于它不是標準C語言函數,所以不能在所有的編譯器中使
用。但是,大多數的編譯器(如Windows上的)通常在<stdlib.h>頭文件中包含這個函數。在<stdlib.h>中與之有相反功能的函數是atoi。功能:把一整數轉換為字符串。