string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
s2ws方法效果良好。希望有帮助。
std::wstring s2ws(const std::string& s) {
std::string curLocale = setlocale(LC_ALL, "");
const char* _Source = s.c_str();
size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
其他回答
使用Boost。地区:
ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
String到wstring
std::wstring Str2Wstr(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
从wstring到String
std::string Wstr2Str(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
Std::string -> wchar_t[]与安全mbstowcs_s函数:
auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());
这是我的示例代码
只有Windows API,前c++ 11实现,以防有人需要它:
#include <stdexcept>
#include <vector>
#include <windows.h>
using std::runtime_error;
using std::string;
using std::vector;
using std::wstring;
wstring utf8toUtf16(const string & str)
{
if (str.empty())
return wstring();
size_t charsNeeded = ::MultiByteToWideChar(CP_UTF8, 0,
str.data(), (int)str.size(), NULL, 0);
if (charsNeeded == 0)
throw runtime_error("Failed converting UTF-8 string to UTF-16");
vector<wchar_t> buffer(charsNeeded);
int charsConverted = ::MultiByteToWideChar(CP_UTF8, 0,
str.data(), (int)str.size(), &buffer[0], buffer.size());
if (charsConverted == 0)
throw runtime_error("Failed converting UTF-8 string to UTF-16");
return wstring(&buffer[0], charsConverted);
}
您可以使用boost路径或std路径;这样就简单多了。 Boost路径更容易用于跨平台应用程序
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
//s to w
std::string s = "xxx";
auto w = fs::path(s).wstring();
//w to s
std::wstring w = L"xxx";
auto s = fs::path(w).string();
如果你喜欢使用std:
#include <filesystem>
namespace fs = std::filesystem;
//The same
c++旧版本
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
//The same
代码内仍然实现了一个转换器,你不必解开细节。