【问题标题】:Portable conversion of std::string to std::wstring and vice versa?std::string 到 std::wstring 的便携式转换,反之亦然?
【发布时间】:2023-03-22 04:02:01
【问题描述】:

我需要将 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'

任何人都可以提供一些方法以独立于平台的方式进行此转换。

【问题讨论】:

  • 你见过this post。答案之一建议使用 Boost.Locale。
  • 是的......这就是为什么我要求解决方案而不是询问这种行为的原因。
  • 由于std::wstringstd::basic_string&lt; wchar_t &gt;,并且wchar_t 本身没有可移植定义(Windows 上为 16 位,其他地方基本上为 32 位),我想说你应该看@ 987654329@,可移植定义的,包括使用的编码......或者更好的是use ICU,因为即使u16string也不完美。
  • 如上所述,使用最新版本的 GCC 和 libstdc++ 应该可以解决 &lt;codecvt&gt; 的直接问题。
  • 您需要使用 G++ 5.1 或更高版本

标签: c++ string wstring codecvt


【解决方案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 示例。

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2018-05-18
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多