欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CString与string、char *类型转换

程序员文章站 2022-07-15 09:19:03
...

字符串处理

win10,VS17中

1.新建MFC工程,选择对话框程序。

CString与string、char *类型转换

2.默认为Unicode字符。为两个按钮添加消息。

CString与string、char *类型转换

CString与string、char *类型转换

void CCStringDlg::OnBnClickedOk()//确定
{
	//string		-->CString
	//char *		-->
	//const char*           -->
	string str = "string1";
	char* s = "char*1";
	const char* ss = "const char*2";

	CString cstr;
	cstr = str.c_str();
	cstr = s;
	cstr = ss;
	GetDlgItem(IDC_STATIC)->SetWindowText(cstr);


	//CString --> string
	//        --> const char*
	CString cstr2 = _T("CString2");

	string str2 = (CStringA)cstr2;
	const char* s2 = str2.c_str();
}
void CCStringDlg::OnBnClickedBtn()//按钮2
{
	//string --> const char*
	//	 --> char*
	string str = "string";

	const char* s = str.c_str();
	char* p = new char[str.length()+1];
	//memset(p,'\0',str.length()+1);
	//strcpy(p, str.c_str());
	strcpy_s(p, str.length() + 1, str.c_str());

	//char* --> string    const char* --> string
	char* s2 = "char *";
	const char* s3 = "const char *";

	string str2 = s2;
	string str3 = s3;

	CString MFCstr;
	MFCstr = p;
	MessageBox(MFCstr, _T("显示"));
}