string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
如果你正在使用Windows/Visual Studio并且需要将字符串转换为wstring,你可以使用:
#include <AtlBase.h>
#include <atlconv.h>
...
string s = "some string";
CA2W ca2w(s.c_str());
wstring w = ca2w;
printf("%s = %ls", s.c_str(), w.c_str());
与将wstring转换为string的过程相同(有时你需要指定一个代码页):
#include <AtlBase.h>
#include <atlconv.h>
...
wstring w = L"some wstring";
CW2A cw2a(w.c_str());
string s = cw2a;
printf("%s = %ls", s.c_str(), w.c_str());
您可以指定一个代码页,甚至UTF8(这在使用JNI/Java时非常好)。将std::wstring转换为utf8 std::string的标准方法显示在这个答案中。
//
// using ATL
CA2W ca2w(str, CP_UTF8);
//
// or the standard way taken from the answer above
#include <codecvt>
#include <string>
// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.from_bytes(str);
}
// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.to_bytes(str);
}
如果你想了解更多关于代码页的知识,在Joel on Software上有一篇有趣的文章:每个软件开发人员绝对必须知道Unicode和字符集的绝对最小值。
这些CA2W(转换Ansi到宽=unicode)宏是ATL和MFC字符串转换宏的一部分,包括样本。
有时你需要禁用安全警告#4995',我不知道其他的解决方法(对我来说,当我在VS2012中为WindowsXp编译时就发生了这种情况)。
#pragma warning(push)
#pragma warning(disable: 4995)
#include <AtlBase.h>
#include <atlconv.h>
#pragma warning(pop)
编辑: 好吧,根据这篇文章,Joel的文章似乎是:“虽然很有趣,但它对实际的技术细节知之甚少”。文章:每个程序员绝对需要知道的关于编码和字符集来处理文本。
其他回答
int StringToWString(std::wstring &ws, const std::string &s)
{
std::wstring wsTmp(s.begin(), s.end());
ws = wsTmp;
return 0;
}
对我来说,最简单又没有大开销的选择是:
包括:
#include <atlbase.h>
#include <atlconv.h>
转换:
char* whatever = "test1234";
std::wstring lwhatever = std::wstring(CA2W(std::string(whatever).c_str()));
如果需要:
lwhatever.c_str();
使用Boost。地区:
ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
string s =“早上好”;is an error。
你应该直接使用wstring:
wstring ws = L"おはよう";
使用这段代码将字符串转换为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;
}