string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
这个版本是我在现实生活中最喜欢的。它将输入(如果它是有效的UTF-8)转换为相应的wstring。如果输入损坏,则用单个字节构造wstring。如果您不能真正确定输入数据的质量,这是非常有用的。
std::wstring convert(const std::string& input)
{
try
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(input);
}
catch(std::range_error& e)
{
size_t length = input.length();
std::wstring result;
result.reserve(length);
for(size_t i = 0; i < length; i++)
{
result.push_back(input[i] & 0xFF);
}
return result;
}
}
其他回答
这个版本是我在现实生活中最喜欢的。它将输入(如果它是有效的UTF-8)转换为相应的wstring。如果输入损坏,则用单个字节构造wstring。如果您不能真正确定输入数据的质量,这是非常有用的。
std::wstring convert(const std::string& input)
{
try
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(input);
}
catch(std::range_error& e)
{
size_t length = input.length();
std::wstring result;
result.reserve(length);
for(size_t i = 0; i < length; i++)
{
result.push_back(input[i] & 0xFF);
}
return result;
}
}
使用这段代码将字符串转换为wstring
std::wstring string2wString(const std::string& s){
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
int main(){
std::wstring str="your string";
std::wstring wStr=string2wString(str);
return 0;
}
从char*到wstring:
char* str = "hello worlddd";
wstring wstr (str, str+strlen(str));
从string到wstring:
string str = "hello worlddd";
wstring wstr (str.begin(), str.end());
注意,只有在被转换的字符串只包含ASCII字符时,这种方法才有效。
您可以使用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
代码内仍然实现了一个转换器,你不必解开细节。
你的问题不明确。严格来说,这个例子是一个语法错误。然而,std::mbstowcs可能是您正在寻找的。
它是一个c库函数,操作缓冲区,但这里有一个易于使用的习语,由Mooing Duck提供:
std::wstring ws(s.size(), L' '); // Overestimate number of code points.
ws.resize(std::mbstowcs(&ws[0], s.c_str(), s.size())); // Shrink to fit.