简体   繁体   中英

Converting string to wstring fails in Visual Studio

The following code is intended to provide a function to convert string in utf-8 to utf-16. But it fails. How can I fix it to work in Visual Studio 2017 C++17:

#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
#include <fstream>
using namespace std;

wstring utf8_to_uft16(string str)
{
    wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert;
    auto p = reinterpret_cast<const wchar_t *>(convert.from_bytes(str).data());
    return wstring(p);
}
int main()
{
    string u8 = u8"hello";
    wstring u16 = utf8_to_uft16(u8);
    wcout << u16;    
    cin.ignore(1);
}

the produced string by the function is empty and nothing is printed.

wstring_convert::from_bytes returns a std::basic_string . This string will be destroyed at the end of the line and the pointer returned from data() will no longer be valid.

Is there a reason you don't just convert directly to wchar_t ?

wstring utf8_to_uft16( string str )
{
  wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
  return convert.from_bytes( str );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM