我正在努力理解C++ unicode,现在我对此感到困惑。
代码:
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;
void trial1(){
string a = "\U00010000z";
cout << a << endl;
u16string b;
std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
b = converter.from_bytes(a);
u16string c = b.substr(0, 1);
string q = converter.to_bytes(c);
cout << q << endl;
}
void trial2(){
u16string a = u"\U00010000";
cout << a.length() << endl; // 2
std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
string b = converter.to_bytes(a);
}
int main() {
// both don't work
// trial1();
// trial2();
return 0;
}我已经测试过,u16string可以将u16string外部的unicode存储为代理项对,例如,u"\U00010000"与2 char16_t一起存储。
那么,为什么std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;不能同时适用于trial1和trial2并引发异常呢?
发布于 2022-02-14 08:10:39
std::codecvt_utf8不支持转换到或从UTF-16,只有UCS-2和UTF-32.您需要使用std::codecvt_utf8_utf16代替。
https://stackoverflow.com/questions/71108289
复制相似问题