CString,字符串,整數(shù)等相互轉(zhuǎn)換方法(推薦)
字符串轉(zhuǎn)int
int atoi(const char *string);
_int64 _atoi64(const char *string);
int _wtoi(const wchar_t *string);
_int64 _ wtoi64(const char *string);
字符串轉(zhuǎn)long
long atol(const char * string);
long _wtol(const wchar_t *string);
字符串轉(zhuǎn)double
double atof(const char *string);
double _wtof(const wchar_t *string);
int轉(zhuǎn)字符串
cahr *_itoa( int value,char *string,int radix);
char *_i64toa(_int64 value,char *string,int radix);
char * _ui64toa(unsigned _int64 value,char *string, int radix);
wchar_t * _itow(int value,wchar_t *string, int radix);
wchar_t * _i64tow(_int64 value,wchar_t *string, int radix);
wchar_t * _ui64tow(unsigned _int64 value,wchar_t *string, int radix);
參數(shù)的意義:value 是指要轉(zhuǎn)換的整數(shù),sring 是用來存放轉(zhuǎn)換后結(jié)果的便利,radix是用來說明轉(zhuǎn)換成幾進(jìn)制的數(shù)據(jù),默認(rèn)值是十進(jìn)制數(shù)的。轉(zhuǎn)換的進(jìn)制范圍是二進(jìn)制到三十六進(jìn)制。
long轉(zhuǎn)字符串
char *_ltoa( long value,char *string, int radix );
wchar_t *_ltow( long value, wchar_t *string, int radix );
其中,參數(shù) value 為被轉(zhuǎn)換的值,參數(shù)string為字符串緩沖區(qū),radix為進(jìn)制。
double轉(zhuǎn)字符串
char *_fcvt( double value, int count, int *dec, int *sign );
其中參數(shù)value 為雙精度數(shù),參數(shù)count為轉(zhuǎn)換的小數(shù)點(diǎn)后面的位數(shù),dec表示小數(shù)點(diǎn)的位置, sign 表示符號。
(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)的第二個(gè)參數(shù)是 const wchar_t* (Unicode)或const char* (ANSI),系統(tǒng)編譯器將會自動對其進(jìn)行轉(zhuǎn)換。
方法三,使用CString::GetBuffer。
如果你需要修改 CString 中的內(nèi)容,它有一個(gè)特殊的方法可以使用,那就是 GetBuffer,它的作用是返回一個(gè)可寫的緩沖指針。 如果你只是打算修改字符或者截短字符串,例如:
CString s(_T("Char test ")); LPTSTR p = s.GetBuffer(); LPTSTR dot = strchr(p, ''.''); // 在這里添加使用p的代碼 if(p != NULL) *p = _T(''); s.ReleaseBuffer();// 使用完后及時(shí)釋放,以便能使用其它的CString成員函數(shù)
在 GetBuffer 和 ReleaseBuffer 之間這個(gè)范圍,一定不能使用你要操作的這個(gè)緩沖的 CString 對象的任何方法。因?yàn)?ReleaseBuffer 被調(diào)用之前,該 CString 對象的完整性得不到保障。
以上就是小編為大家?guī)淼腃String,字符串,整數(shù)等相互轉(zhuǎn)換方法(推薦)的全部內(nèi)容了,希望對大家有所幫助,多多支持腳本之家~
相關(guān)文章
C++實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)(完整版)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06C++?OpenCV實(shí)現(xiàn)白平衡之完美反射算法
完美反射算法是白平衡各種算法中較常見的一種,比灰度世界算法更優(yōu)。本文將利用C++和OpenCV實(shí)現(xiàn)白平衡中的完美反射算法,需要的可以參考一下2022-05-05