MFC 類型轉換
一、CString與LPSTR、LPCSTR、string、 char*相互轉換
1. CString轉換成LPSTR:方法一:
1 CString strFileName;
2 LPSTR lpStr = strFileName.GetBuffer();
3 strFileName.ReleaseBuffer();
方法二:
1 CString strFileName;
2 LPSTR lpStr = (LPSTR)(LPCSTR)strFimeName;
3
2. LPSTR轉換成CString:
1 LPSTR lpStr = _T("TestStr");
2 CString str(lpStr);
3 //注意:CString和LPCSTR可直接轉換,如下:
4 CString str;
5 LPCSTR lpcStr = (LPCSTR)str;
CString轉換成LPSTR:
CString strTemp;
LPTSTR pSterTemp = strTemp.GetBuffer(); //這會為pSetTemp指向的字符串分配內存,同時會把strTemp的內容拷貝下來。。
strTemp.ReleaseBuffer(); //must call this funtion. 歸還內存給操作系統。
或:
LPTSTR pSterTemp = (LPTSTR)(LPCSTR)strTemp;
3.string 轉 CString
1 CString.format("%s", string.c_str());
4.CString 轉 string
1 string s(CString.GetBuffer(CString.GetLength()));
5. CString轉char*
(1)傳給未分配內存的const char* (LPCTSTR)指針.
1 CString cstr(asdd);
2 const char* ch = (LPCTSTR)cstr;
3 //ch指向的地址和cstr相同。但由于使用const保證ch不會修改,所以安全.
(2)傳給未分配內存的指針.
CString cstr = "ASDDSD";
char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);
cstr.ReleaseBuffer();
//修改ch指向的值等于修改cstr里面的值.
//PS:用完ch后,不用delete ch,因為這樣會破壞cstr內部空間,容易造成程序崩潰.
(3)第二種用法。把CString 值賦給已分配內存的char *.
1 CString cstr1 = "ASDDSD";
2 int strLength = cstr1.GetLength() + 1;
3 char *pValue = new char[strLength];
4 strncpy(pValue, cstr1, strLength);
(4)第三種用法.把CString 值賦給已分配內存char[]數組.
1 CString cstr2 = "ASDDSD";
2 int strLength1 = cstr1.GetLength() + 1;
3 char chArray[100];
4 memset(chArray,0, sizeof(bool) * 100); //將數組的垃圾內容清空.
6、char * 轉 CString
1 CString.format("%s", char*);
二、string與char*轉換
1、char * 轉 string
1 string s(char *);
2、string 轉 char *
1 char *p = string.c_str();
三、CString轉換到TCHAR *
1、使用強制轉換。例如:
1 CString theString( "This is a test" );
2 LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
2、使用strcpy。例如:
1 CString theString( "This is a test" );
2 LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
3 _tcscpy(lpsz, theString);
4
5 //需要說明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二個參數是 const wchar_t* (Unicode)或const char* (ANSI),系統編譯器將會自動對其進行轉換。
3、使用CString::GetBuffer。例如:
1 CString s(_T("This is a test "));
2 LPTSTR p = s.GetBuffer();
3 // 在這里添加使用p的代碼
4 if(p != NULL) *p = _T('\0');
5 s.ReleaseBuffer();
6 // 使用完后及時釋放,以便能使用其它的CString成員函數
四、string轉wstring
1 wchar_t wcs[100], wc;
2
3 string testStr1="1234567890";
4
5 setlocale(LC_CTYPE, ""); //很重要,沒有這一句,轉換會失敗
6
7 mbstowcs(wcs, testStr1.c_str(), 99);
8
9 wstring testStr(wcs);
#include <string>
std::string ws2s(const std::wstring& ws)
{
std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);
wcstombs(_Dest,_Source,_Dsize);
std::string result = _Dest;
delete []_Dest;
_Dest = NULL;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
std::wstring s2ws(const std::string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
_Dest = NULL;
setlocale(LC_ALL, "C");
return result;
}
C語言庫函數名: atoi 功 能: 把字符串轉換成整型數
函數名: atof 功 能: 把字符串轉換成浮點數
CString與Byte數組相互轉換
CString cs1 = "gettruckpos";
byte buf[200];
memcpy(buf,cs1.GetBuffer(cs1.GetLength()),cs1.GetLength()); //將cstring放入byte數組
CString *pPhoneNum =new CString((char*)buf, cs1.GetLength()); //將byte數組轉換成cstring
CString cs2 = *pPhoneNum;
int轉byte
//int轉byte
void intToByte(int i,byte *bytes,int size = 4)
{
byte[] bytes = new byte[4];
memset(bytes,0,sizeof(byte) * size);
bytes[0] = (byte) (0xff & i);
bytes[1] = (byte) ((0xff00 & i) >> 8);
bytes[2] = (byte) ((0xff0000 & i) >> 16);
bytes[3] = (byte) ((0xff000000 & i) >> 24);
return ;
}
BYTE* IntToBytes(int nNum, BOOL isHighFirst, BYTE *pVal)
{
BYTE result[4] = {0};
if (isHighFirst)
{
result[0] = (BYTE)(nNum >> 24 & 0xff);
result[1] = (BYTE)(nNum >> 16 & 0xff);
result[2] = (BYTE)(nNum >> 8 & 0xff);
result[3] = (BYTE)(nNum & 0xff);
}
else
{
result[3] = (BYTE)(nNum >> 24 & 0xff);
result[2] = (BYTE)(nNum >> 16 & 0xff);
result[1] = (BYTE)(nNum >> 8 & 0xff);
result[0] = (BYTE)(nNum & 0xff);
}
memcpy(pVal, result, 4);
return result;
}
byte轉int
//byte轉int
int bytesToInt(byte* bytes,int size = 4)
{
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
CString轉 wchar_t*wchar_t * CCommonFun::ConvertCStringToWchar_t(CString &str)
{
CString sTemp = str;
const char* CStr = (LPCTSTR)sTemp;
size_t len = strlen(CStr) + 1;
size_t converted = 0;
wchar_t *WStr;
WStr = (wchar_t*)malloc(len*sizeof(wchar_t));
mbstowcs_s(&converted, WStr, len, CStr, _TRUNCATE);
return WStr;
}
注意:可以在調用的地方釋放分配的內存,如果遇到漢子轉換亂碼問題可以在轉換前使用setlocale(LC_ALL, "chs")或者setlocale(LC_ALL,"zh_CN.UTF-8")進行設置wchar_t*轉CStringCString CTestTextToPicDlg::ConvertWchar_tToCString(const wchar_t* WStr)
{
size_t len = wcslen(WStr) + 1;
size_t converted = 0;
char *CStr;
CStr=(char*)malloc(len*sizeof(char));
wcstombs_s(&converted, CStr, len, WStr, _TRUNCATE);
CString sTemp;
sTemp.Format("%s", CStr);
free(CStr);
CStr = NULL;
return sTemp;
}
TCHAR和char的區別:
C++支持兩種字符串,即常規的ANSI編碼(使用""包裹)和Unicode編碼(使用L""包裹),這樣對應的就有了兩套字符串字符串處理函數,比如:strlen和wstrlen,分別用于處理兩種字符串。
由于字符編碼的不同,在C++中有三種對于字符類型:char, wchar_t , TCHAR。其實TCHAR不能算作一種類型,他緊緊是一個宏。我們都知道,宏在預編譯的時候會被替換成相應的內容。TCHAR 在使用多字節編碼時被定義成char,在Unicode編碼時定義成wchar_t。
如果你希望同時為ANSI和Unicode編譯的源代碼,那就要include TChar.h。TCHAR是定義在其中的一個宏,它視你是否定義了_UNICODE宏而定義成char或者wchar_t。如果你使用了TCHAR,那么就不應該使用ANSI的strXXX函數或者Unicode的wcsXXX函數了,而必須使用TChar.h中定義的_tcsXXX函數。另外,為了解決剛才提到帶“L”的問題,TChar.h中定義了一個宏:“_TEXT”。
以strcpy函數為例子,總結一下:
.如果你想使用ANSI字符串,那么請使用這一套寫法:
char szString[100];
strcpy(szString,"test");
.如果你想使用Unicode字符串,那么請使用這一套:
wchar_t szString[100];
wcscpyszString,L"test");
.如果你想通過定義_UNICODE宏,而編譯ANSI或者Unicode字符串代碼:
TCHAR szString[100];
_tcscpy(szString,_TEXT("test"));
使用TCHAR系列方案編寫程序
TCHAR是一種字符串類型,它讓你在以MBCS和UNNICODE來build程序時可以使用同樣的代碼,不需要使用繁瑣的宏定義來包含你的代碼。
TCHAR的引入,主要是在Tchar.h文件中,該文件包含這方面的重要的定義信息。
對于包含了對str函數或wcs函數進行顯式調用的代碼來說,無法非常容易地同時為ANSI和Unicode對這些代碼進行編譯。本章前面說過,可以創建同時為ANSI和Unicode進行編譯的單個源代碼文件。若要建立雙重功能,必須包含TChar.h文件,而不是包含String.h文件。
TChar.h文件的唯一作用是幫助創建ANSI/Unicode通用源代碼文件。它包含你應該用在源代碼中的一組宏,而不應該直接調用str函數或者 wcs函數。如果在編譯源代碼文件時定義了_UNICODE,這些宏就會引用wcs這組函數。如果沒有定義_UNICODE,那么這些宏將引用str這組宏。
TCHAR的定義如下:
#ifdef UNICODE
typedef wchar_t TCHAR;
#else
typedef char TCHAR;
#endif
所以用MBCS來build時,TCHAR是char,使用UNICODE時,TCHAR是wchar_t。
還有一個宏來處理定義Unicode字符串常量時所需的L前綴。
#ifdef UNICODE
#define _T(x) L##x
#define _TEXT(x) L##x
#define __T(x) L##x
#else
#define _T(x) x
#define _TEXT(x) x
#define __T(x) x
#endif
## 是一個預處理操作符,它可以把兩個參數連在一起。如果你的代碼中需要字符串常量,在它前面加上_T宏。如果你使用Unicode來build,它會在字符串常量前加上L前綴。
TCHAR szNewText[] = _T("we love Bob!");
_UNICODE宏用于C運行期頭文件,而UNICODE宏則用于Windows頭文件。當編譯源代碼模塊時,通常必須同時定義這兩個宏。
像是用宏來隱藏SetWindowTextA/W的細節一樣,還有很多可以供你使用的宏來實現str***()和_mbs***()等字符串函數。例如,你可以使用_tcsrchr宏來替換strrchr()、_mbsrchr()和wcsrchr()。_tcsrchr根據你預定義的宏是_MBCS還是 UNICODE來擴展成正確的函數,就象SetWindowText所作的一樣。
不僅str***()函數有TCHAR宏。其他的函數如, _stprintf(代替sprinft()和swprintf()),_tfopen(代替fopen()和_wfopen())。 MSDN中"Generic-Text Routine Mappings."標題下有完整的宏列表。
QT類型轉換
Qstring str;
char* ch;
QByteArray ba = str.toLatin1();
ch=ba.data();
這樣就完成了QString向char*的轉化。經測試程序運行時不會出現bug
注意第三行,一定要加上,不可以str.toLatin1().data()這樣一部完成,可能會出錯。
補充:以上方法當QString里不含中文時,沒有問題,但是QString內含有中文時,轉換為char*就是亂碼,采用如下方法解決:
方法1:
添加GBK編碼支持:
#include <QTextCodec>
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
然后改變上面的第三行為:QByteArray ba = str.toLoacl8Bit(); toLoacl8Bit支持中文
方法2:
先將QString轉為標準庫中的string類型,然后將string轉為char*,如下:
std::string str = filename.toStdString();
const char* ch = str.c_str();
posted on 2012-04-06 17:08
王海光 閱讀(1001)
評論(0) 編輯 收藏 引用 所屬分類:
C++