c++ - Why is wstring_convert throwing a range_error? -
i'm writing code needs convert between byte strings , wide strings, using system locale. when reading file, incredibly easy do. can use std::wifstream
, imbue std::locale("")
, , use std::getline
.
according cppreference's codecvt page, wifstream
uses codecvt<wchar_t, char, mbstate_t>
, thought might able convert between std::string
, std::wstring
using well:
// utility wrapper adapt locale-bound facets 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::locale::global(std::locale("")); std::wstring_convert< deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> wconv; std::wstring wstr = wconv.from_bytes(data);
however, when try run this, range_error
thrown wstring_convert
. did googling around, , apparently happens when wstring_convert
fails convert string.
however, these strings able converted using wfstream
, should using same codecvt
using wstring_convert
. why wifstream
work, wstring_convert
not?
and there way can convert between string
s , wstring
s using system's locale?
a full example of problem, adapted codecvt page, here, , output is:
sizeof(char32_t) = 4 sizeof(wchar_t) = 4 utf-8 file contains following ucs4 code points: u+007a u+00df u+6c34 u+1f34c utf-8 string contains following ucs4 code points: u+007a u+00df u+6c34 u+1f34c terminate called after throwing instance of 'std::range_error' what(): wstring_convert aborted (core dumped)
yourwifstream
, wstring_convert
using different facets.
wifstream
using locale-dependent conversion facet; pulls out of std::locale("")
, imbued, via std::use_facet
wstring_convert
given locale-independent, standalone codecvt facet, , 1 provided implementation apparently not convert utf-8 fitting; try calling in on directly see does.
an easy way locale-dependent facet ask name, in std::codecvt_byname
Comments
Post a Comment