2

I need to convert std::string to std::wstring. I have used something on below lines with visual studio 2010 (and it's working fine) :-

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::string narrow = converter.to_bytes(wide_utf16_source_string); std::wstring wide = converter.from_bytes(narrow_utf8_source_string); 

However, when I build it on gcc 4.3.4, it gives error :-

 .cxx:333: error: 'wstring_convert' is not a member of 'std' .cxx:333: error: 'codecvt_utf8_utf16' is not a member of 'std' 

Can anyone please provide me some way to do this conversion in platform independent way.

12
  • Have you seen this post. One of the answers suggests using Boost.Locale. Commented Apr 26, 2016 at 11:19
  • Yes...And that's why I asked for solution rather than asking reason for this behaviour. Commented Apr 26, 2016 at 11:20
  • 1
    Since std::wstring is std::basic_string< wchar_t >, and wchar_t itself is not portably defined (16 bits on Windows, 32 bits basically everywhere else), I'd say you should rather be looking at std::u16string, which is portably defined, including the encoding used... or, even better, use ICU because even u16string isn't perfect. Commented Apr 26, 2016 at 11:21
  • The above being said, using an up-to-date version of GCC and libstdc++ should solve the immediate problem with <codecvt>. Commented Apr 26, 2016 at 11:25
  • 1
    You will need to use G++ 5.1 or later Commented Apr 26, 2016 at 11:31

1 Answer 1

0
#include <codecvt> #include <locale> // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert template<class Facet> struct deletable_facet : Facet { template<class ...Args> deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {} ~deletable_facet() {} }; std::string wstr2str(const wchar_t* wstr) { std::wstring source(wstr); std::wstring_convert<deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>, wchar_t> convert; std::string dest = convert.to_bytes(source); return dest; } 

Based on https://en.cppreference.com/w/cpp/locale/codecvt example.

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.