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

后端 未结 16 2208
难免孤独
难免孤独 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:34

    This variant of it is my favourite in real life. It converts the input, if it is valid UTF-8, to the respective wstring. If the input is corrupted, the wstring is constructed out of the single bytes. This is extremely helpful if you cannot really be sure about the quality of your input data.

    std::wstring convert(const std::string& input)
    {
        try
        {
            std::wstring_convert> 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;
        }
    }
    

提交回复
热议问题