Skip to content

Instantly share code, notes, and snippets.

@Temptationx
Created December 2, 2017 12:54
Show Gist options
  • Save Temptationx/0e107e446918cc7f3ed9bb221c32dc02 to your computer and use it in GitHub Desktop.
Save Temptationx/0e107e446918cc7f3ed9bb221c32dc02 to your computer and use it in GitHub Desktop.
wstring与string相互转换
#include <string>
#include <locale.h>
// 需包含locale、string头文件、使用setlocale函数。
std::wstring StringToWstring(const std::string str)
{// string转wstring
unsigned len = str.size() * 2;// 预留字节数
setlocale(LC_CTYPE, ""); //必须调用此函数
wchar_t *p = new wchar_t[len];// 申请一段内存存放转换后的字符串
mbstowcs(p,str.c_str(),len);// 转换
std::wstring str1(p);
delete[] p;// 释放申请的内存
return str1;
}
std::string WstringToString(const std::wstring str)
{// wstring转string
unsigned len = str.size() * 4;
setlocale(LC_CTYPE, "");
char *p = new char[len];
wcstombs(p,str.c_str(),len);
std::string str1(p);
delete[] p;
return str1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment