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

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

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


当前回答

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

你应该直接使用wstring:

wstring ws = L"おはよう";

其他回答

从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字符时,这种方法才有效。

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

    ws = wsTmp;

    return 0;
}

只有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);
}

对我来说,最简单又没有大开销的选择是:

包括:

#include <atlbase.h>
#include <atlconv.h>

转换:

char* whatever = "test1234";
std::wstring lwhatever = std::wstring(CA2W(std::string(whatever).c_str()));

如果需要:

lwhatever.c_str();

这个版本是我在现实生活中最喜欢的。它将输入(如果它是有效的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;
    }
}