string s = "おはよう";
wstring ws = FUNCTION(s, ws);

如何将s的内容分配给ws?

搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。


当前回答

根据我自己的测试(在windows 8上,vs2010) mbstowcs实际上可以破坏原始字符串,它只适用于ANSI代码页。If MultiByteToWideChar/WideCharToMultiByte也会导致字符串损坏-但他们倾向于用'?'问号,但mbstowcs往往会在遇到未知字符时停止,并在此时切断字符串。(我在芬兰语窗口上测试过越南字符)。

所以更喜欢Multi* windows api函数而不是模拟ansi C函数。

我还注意到,从一个代码页到另一个代码页编码字符串的最短方法不是使用MultiByteToWideChar/WideCharToMultiByte api函数调用,而是它们的模拟ATL宏:W2A / A2W。

所以如上所述的模拟函数听起来是这样的:

wstring utf8toUtf16(const string & str)
{
   USES_CONVERSION;
   _acp = CP_UTF8;
   return A2W( str.c_str() );
}

_acp在USES_CONVERSION宏中声明。

或者在执行旧数据到新数据的转换时,我经常错过的函数:

string ansi2utf8( const string& s )
{
   USES_CONVERSION;
   _acp = CP_ACP;
   wchar_t* pw = A2W( s.c_str() );

   _acp = CP_UTF8;
   return W2A( pw );
}

但请注意,这些宏使用大量的堆栈-不要为同一个函数使用for循环或递归循环-在使用W2A或A2W宏后-最好尽快返回,因此堆栈将从临时转换中释放出来。

其他回答

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());

这是我的示例代码

如果你有QT,如果你懒得实现一个函数和东西,你可以使用

std::string str;
QString(str).toStdWString()
int StringToWString(std::wstring &ws, const std::string &s)
{
    std::wstring wsTmp(s.begin(), s.end());

    ws = wsTmp;

    return 0;
}

string s =“早上好”;is an error。

你应该直接使用wstring:

wstring ws = L"おはよう";

您可以使用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

代码内仍然实现了一个转换器,你不必解开细节。