VC\MFC当中CString、string、char、char*、char数组、int等类型之间的转换令人晕头转向,特地搜集多篇文章资料,利用代码实例等清晰的理清他们之间的关系和如何转换,其实非常简单。
1、CString std::string互转
std::string strstring = "std::string";
CString strCString = _T("CString");
//CString->std::string
strstring = CStringA(strCString);
//std::string->CString
strCString = strstring.c_str();
2、int和CString
//CString->int
CString strInt = _T("123");
int n = 0;
n = _ttoi(strInt);
n = 9;
//int->CString
strInt.Format(_T("%d"), n);
3、double和CString
CString strdouble = _T("123.00");
double dVal = 0;
//CString->double
dVal = _tstof(strdouble);
dVal = 999.0;
//double->CString
strdouble.Format(_T("%f"), dVal);
//4、char*和CString
char* chchar = "chahdaslhdf";
CString strCh = _T("char");
//char*->CString
strCh = chchar;
//或者
//预转换,得到所需空间的大小
int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, chchar, strlen(chchar), NULL, 0);
//分配空间要给‘\0‘留个空间,MultiByteToWideChar不会给‘\0‘空间
wchar_t* wszString = new wchar_t[wcsLen + 1];
//转换
::MultiByteToWideChar(CP_ACP, NULL, chchar, strlen(chchar), wszString, wcsLen);
//最后加上‘\0‘
wszString[wcsLen] = ‘\0‘;
//附加到CString对象上
CString content;
content.Append(wszString);
//CString->char*
int len=strCh.GetLength();
char *buffer=new char[len+1];
memset(buffer,0,len+1);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)strCh, -1,NULL, 0, NULL, FALSE);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)strCh, -1,(LPSTR)buffer, len, NULL, FALSE);
buffer[len]=‘\0‘;
delete []buffer;
5、将wchar_t*转化为char*
char* UnicodeToAnsi(const wchar_t* szStr)
{
int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
if (nLen == 0)
return NULL;
char* pResult = new char[nLen+1];
WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
return pResult;
}
6、将char*转化为wchar_t*
wchar_t* AnsiToUnicode(const char* szStr)
{
int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );
if (nLen == 0)
return NULL;
wchar_t* pResult = new wchar_t[nLen+1];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
return pResult;
}