1

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.

1 Answer 1

4

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 ); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.