您的位置:首页 > 其它

Unicode编码的项目中CString、char* 、wstring、string的相互转换

2016-03-12 20:27 344 查看
在多字节字符集项目下面CString转char*不是什么问题,但现在都流行使用unicode字符集,而且也是微软推荐的。那么由于字符集的问题CString转char*就会出现一定的问题,必须要有特殊的方法才行,以下是结合网上的一些资料和自己实践出来的两个方法:

1、CString转char* 可以使用以下函数:

static char* StringToChar(CString str){
//获取字符串大小
int len = WideCharToMultiByte(CP_ACP, 0, str, str.GetLength(), NULL, 0, NULL, NULL);
//为多字节字符数组申请空间,数组大小为按字节计算的宽字节字节大小
char* p = new char[len + 1];		//以字节为单位
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP, 0, str, str.GetLength()+1, p, len+1, NULL, NULL);
p[len + 1] = '/0';   //多字节字符以'/0'结束
return p;
}
这个函数有可能会造成内存溢出的错误


2、CString转string和char*

CString str=_T("测试");
CStringA strA= str.GetBuffer(0);
string stdStr = strA.GetBuffer();

char* p=stdStr.c_str();


3、wstring转string

//将wstring转换成string
static string ws2s(wstring wstr)
{
if (wstr.empty())return "";
string result;
//获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
char* buffer = new char[len + 1];
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
//删除缓冲区并返回值
result.append(buffer);
delete[] buffer;
return result;
}

4、string转wstring

//将string转wstring
static wstring s2ws(const string& s){
if (s.empty())return L"";
size_t convertedChars = 0;
string curLocale = setlocale(LC_ALL, NULL);   //curLocale="C"
setlocale(LC_ALL, "chs");
const char* source = s.c_str();
size_t charNum = sizeof(char)*s.size() + 1;
wchar_t* dest = new wchar_t[charNum];
mbstowcs_s(&convertedChars, dest, charNum, source, _TRUNCATE);
wstring result = dest;
delete[] dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息