C++ Convert string (or char*) to wstring (or wchar_t*)

后端 未结 16 2500
难免孤独
难免孤独 2020-11-22 05:57
string s = \"おはよう\";
wstring ws = FUNCTION(s, ws);

How would i assign the contents of s to ws?

Searched google and used some techniques but

16条回答
  •  暖寄归人
    2020-11-22 06:30

    Windows API only, pre C++11 implementation, in case someone needs it:

    #include 
    #include 
    #include 
    
    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 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);
    }
    

提交回复
热议问题