🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
##实战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()); ~~~ [](http://blog.csdn.net/wangshubo1989/article/details/50274079#)[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到QQ空间")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到新浪微博")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到腾讯微博")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到人人网")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到微信")