#include <Windows.h>
//將string轉換成wstring
wstring string2wstring(string str)
{
wstring result;
//獲取緩衝區大小,並申請空間,緩衝區大小按字符計算
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
TCHAR* buffer = new TCHAR[len + 1];
//多字節編碼轉換成寬字節編碼
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0'; //添加字符串結尾
//刪除緩衝區並返回值
result.append(buffer);
delete[] buffer;
return result;
}
//將wstring轉換成string
string wstring2string(wstring wstr)
{
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;
}
Windows下,string與wstring互轉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.