目录
在mfc中,char* ,CString,string之间的转换是使用非常频繁的,这里参考了网上的许多方法,这里做一个总结
CString转char *
void CString_to_chars()
{
char ch[256];
CString cs = _T("this is test CString_to_chars");
#ifndef UNICODE
int str_len = cs.GetLength();
char *buf = cs.GetBuffer(str_len);
memcpy(ch, buf, str_len);
ch[str_len] = '\0';
cs.ReleaseBuffer();
#else
int len = WideCharToMultiByte(CP_ACP, 0, cs, -1, NULL, 0, NULL, NULL);//m_csFileName.GetLength()
WideCharToMultiByte(CP_ACP, 0, cs, -1, ch, len, NULL, NULL);
ch[len + 1] = '\0';
#endif
printf("%s\n", ch);
}
char *转CString
void chars_to_CString()
{
CString cs;
const char *ch = "this is test chars_to_CString";
const char ch2[] = "this is test chars_to_CString";
cs = ch;
//cs = ch2;
//cWnd->SetDlgItemText(IDC_EDIT_CSTRING_OUTPUT, cs);
}
string转char *
void string_to_chars()
{
string ss = "this is test string_to_chars";
char ch[256];
memcpy(ch, ss.c_str(), ss.length() + 1);
printf("%s\n", ch);
}
char *转string
void chars_to_string()
{
string ss;
const char *ch = "this is test chars_to_string";
const char ch2[] = "this is test chars_to_string";
ss = ch;
//ss = ch2;
cout << ss << endl;
}
CString转string
void CString_to_string()
{
string ss;
CString cs = _T("this is test CString_to_string");
#if 1 //方法一
ss = CT2A(cs.GetString());
#else //方法二
#ifndef UNICODE
ss = CA2A(cs.GetString());
#else
ss = CW2A(cs.GetString());
#endif
#endif
cout << ss << endl;
}
string转CString
void string_to_CString()
{
string ss = "this is test string_to_CString";
CString cs;
#if 1 //方法一
cs = CA2T(ss.c_str());
#else //方法二
#ifndef UNICODE
cs = CA2A(ss.c_str());
#else
cs = CA2W(ss.c_str());
#endif
#endif
//cWnd->SetDlgItemText(IDC_EDIT_CSTRING_OUTPUT, cs);
}
其他的还有char转int,string转int等等,相关资料包括demo代码请到我<MFC实用技巧>篇最下的网盘链接中下载!