CString => char* 변환
char * ch;
CString *str;
1) ch = (LPSTR)(LPCSTR)str;
2) ch = str.GetBuffer(str.GetLength());
3) wsprintf( ch, "%s", str);
char* => CString 변환
1) str = (LPCSTR)(LPSTR)ch;
2) str = ch;
CString => int 변환
int a;
CString strTest = _T("abc");
a = _ttoi(strTest);
문자열에서 숫자만 추출하기
CString str = _T("abc123def456");
CString strNumber(_T(""));
for(int i = 0; i < str.GetLength(); i++){
char ch = str.GetAt(i);
if(ch >= '0' && ch <= '9')
strNumber += ch;
}
int final = _ttoi(strNumber);
// CString -> int convertCString
strNum = _T("5");
int nNum = _ttoi(strNum);
// int -> CString convertint
nNum = 5;
CString strNum;
strNum.Format(_T("%d"), nNum);
// CString -> doubleCString
strNum = _T("5.5");
double nNum = _wtof(strNum);
// double -> CStringdouble
nNum = 5.5;
CString strNum;
strNum.Format(_T("%f"), nNum);
// Multibyte 기반일 경우// _ttoi -> atoi
// _wtof -> atof 로 바꿔주면 됩니다.
참고)
LPSTR 은 char* 입니다.
LPSTR : char stirng의 32비트 포인터, char* 와 같다.
LPCTSTR : Constant character String의 32비트 포인터
UINT : 32비트 unsigned형 정수
DWORD : unsigned long int형
BYTE : 8비트 unsigned 정수
1.CString 클래스의 GetBuffer()는 CString을 char *로 바꿔줍니다.
ex) CString strTemp = _T("test");
char *getTemp=NULL;
getTemp = malloc(strTemp.GetLength()+1);
strcpy(getTemp, strTemp.GetBuffer(strTemp.GetLength());
printf("결과:%sn", getTemp);
free(getTemp);
2. operator LPCTSTR ()도 마찬가지입니다.
ex) CString strTemp = _T("test");
char *getTemp = (LPSTR)(LPCSTR)strData;
int i=atoi(msg.type);
error C2664: 'atoi' : cannot convert parameter 1 from 'class CString' to 'const char *'
what should I do?
In this case, you don't need to convert if you use the UNICODE version of atoi, _wtoi. Even better is to use _ttoi, which is the TCHAR version and will work for both UNICODE and MBCS: If UNICODE is defined, it will accept a const wchar_t*, if not, a const char*. You don't even need the explicit cast to LPCTSTR, as it will be invoked automatically:
And please don't listen to people who tell you to use CString::GetBuffer() in this situation, they don't know what they are talking about. GetBuffer() is used exclusively to gain write access to CString's internal buffer, not to convert from CString to char*. And if you don't be careful to match every GetBuffer() call with ReleaseBuffer(), using that CString object will produce unpredictable results.
'old drawer > C, C++, MFC' 카테고리의 다른 글
[MFC] CEdit 입력 제어 (0) | 2012.07.19 |
---|---|
[MFC] SetWindowPos() 윈도우 위치 및 크기 등의 변경 (0) | 2012.07.19 |
[MFC] CEdit Styles (0) | 2012.07.13 |
[MFC] GetDlgItem() (0) | 2012.07.12 |
[MFC] 특정 영역 속에 마우스 클릭시 이벤트 발생법 (0) | 2012.07.12 |