2

我需要将 std::string 转换为 std::wstring。我在 Visual Studio 2010 的以下行中使用了一些东西(并且工作正常):-

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

但是,当我在其上构建它时gcc 4.3.4,它会给出错误:-

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

谁能给我一些方法来以独立于平台的方式进行这种转换。

4

1 回答 1

1
#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;
}

基于https://en.cppreference.com/w/cpp/locale/codecvt示例。

于 2020-09-23T04:55:00.777 回答