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.
#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.
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.