在多字節字符集項目下面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;
}