clang:将const char16_t*(UTF-16)转换为wstring(UCS-4)

rya*_*ner 3 c++ unicode macos clang c++11

我正在尝试将UTF-16编码的字符串转换为UCS-4

如果我理解正确,C++ 11通过codecvt_utf16提供此转换.

我的代码是这样的:

#include <iostream>
#include <locale>
#include <memory>
#include <codecvt>
#include <string>

using namespace std;

int main()
{
    u16string s;

    s.push_back('h');
    s.push_back('e');
    s.push_back('l');
    s.push_back('l');
    s.push_back('o');

    wstring_convert<codecvt_utf16<wchar_t>, wchar_t> conv;
    wstring ws = conv.from_bytes(reinterpret_cast<const char*> (s.c_str()));

    wcout << ws << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:显式的push_backs来解决我的clang版本(Xcode 4.2)没有unicode字符串文字这一事实.

代码运行时,我得到终止异常.我在这里做违法的事吗?我认为它应该工作,因为我传递给wstring_convert的const char*是UTF-16编码的,对吧?我也认为字节顺序是问题,但我已经检查过情况并非如此.

Cub*_*bbi 9

两个错误:

1)带有from_bytes()单个的重载需要const char*一个以空字符结尾的字节串,但是你的第二个字节是'\ 0'.

2)您的系统可能是little-endian,因此您需要从UTF-16LE转换为UCS-4:

#include <iostream>
#include <locale>
#include <memory>
#include <codecvt>
#include <string>

using namespace std;

int main()
{
    u16string s;

    s.push_back('h');
    s.push_back('e');
    s.push_back('l');
    s.push_back('l');
    s.push_back('o');

    wstring_convert<codecvt_utf16<wchar_t, 0x10ffff, little_endian>,
                     wchar_t> conv;
    wstring ws = conv.from_bytes(
                     reinterpret_cast<const char*> (&s[0]),
                     reinterpret_cast<const char*> (&s[0] + s.size()));

    wcout << ws << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Windows上使用Visual Studio 2010 SP1和在Linux上使用CLang ++/libc ++ - svn进行测试.