Hossein Khass
Hossein Khass

Reputation: 13

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.

Upvotes: 1

Views: 261

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36614

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

Upvotes: 4

Related Questions