实战c++中的string系列--std::string与MFC中CString的转换

时间:2023-03-10 05:36:58
实战c++中的string系列--std::string与MFC中CString的转换

搞过MFC的人都知道cstring,给我们提供了非常多便利的方法。

CString 是一种非常实用的数据类型。

它们非常大程度上简化了MFC中的很多操作,使得MFC在做字符串操作的时候方便了非常多。无论如何,使用CString有非常多特殊的技巧,特别是对于纯C背景下走出来的程序猿来说有点难以学习。

可是非常多情况下,我们还是须要cstring和string的转换。

分两步:

1把cstring转为char数组

2依据char数组,构造自己的string(记得释放内存)

std::string CStringToSTDStr(const CString& theCStr)
{
const int theCStrLen = theCStr.GetLength();
char *buffer = (char*)malloc(sizeof(char)*(theCStrLen+1));
memset((void*)buffer, 0, sizeof(buffer));
WideCharToMultiByte(CP_UTF8, 0, static_cast<cstring>(theCStr).GetBuffer(), theCStrLen, buffer, sizeof(char)*(theCStrLen+1), NULL, NULL); std::string STDStr(buffer);
free((void*)buffer);
return STDStr;
}

而string转cstring那就非常轻松了:

string str="abcde";
CString cstr(str.c_str());