Closed ayakasuki closed 9 months ago
现在支持了,就是字符串处理有亿点问题
现在支持了,就是字符串处理有亿点问题
参考一下,昨天调过了没问题。
代码:
#include <iostream>
#include <vector>
#include <string>
#include <locale>
#include <iconv.h>
std::wstring utf8_to_utf16le(const std::string& utf8_str) {
iconv_t conv = iconv_open("UTF-16LE", "UTF-8");
if (conv == (iconv_t)-1) {
perror("iconv_open");
return L"";
}
size_t in_bytes_left = utf8_str.size();
size_t out_bytes_left = in_bytes_left * sizeof(wchar_t);
std::vector<char> outbuf(out_bytes_left, 0);
char* in_buf = const_cast<char*>(utf8_str.data());
char* out_ptr = outbuf.data();
if (iconv(conv, &in_buf, &in_bytes_left, &out_ptr, &out_bytes_left) == (size_t)-1) {
perror("iconv");
iconv_close(conv);
return L"";
}
iconv_close(conv);
std::wstring utf16_str(reinterpret_cast<wchar_t*>(outbuf.data()), outbuf.size() / sizeof(wchar_t));
return utf16_str;
}
std::string utf16le_to_utf8(const std::wstring& utf16_str) {
iconv_t conv = iconv_open("UTF-8", "UTF-16LE");
if (conv == (iconv_t)-1) {
perror("iconv_open");
return "";
}
size_t in_bytes_left = utf16_str.size() * sizeof(wchar_t);
size_t out_bytes_left = in_bytes_left;
std::vector<char> outbuf(out_bytes_left, 0);
char* in_buf = reinterpret_cast<char*>(const_cast<wchar_t*>(utf16_str.data()));
char* out_ptr = outbuf.data();
if (iconv(conv, &in_buf, &in_bytes_left, &out_ptr, &out_bytes_left) == (size_t)-1) {
perror("iconv");
iconv_close(conv);
return "";
}
iconv_close(conv);
return std::string(outbuf.data());
}
测试代码:
static void set_locale()
{
std::locale::global(std::locale(""));
// std::locale::global(std::locale("zh_CN.UTF-8"));
}
int main() {
set_locale();
std::cout << u8"测试中文输出显示" << "\n";
std::string utf8_string = u8"你好,世界!";
std::wstring utf16le_string = utf8_to_utf16le(utf8_string);
std::string converted_back_to_utf8 = utf16le_to_utf8(utf16le_string);
std::cout << "Original UTF-8 string: " << utf8_string.c_str() << std::endl;
std::cout << "Converted to UTF-16 LE and back to UTF-8: " << converted_back_to_utf8.c_str() << std::endl;
return 0;
}
已经支持
如题,因为本身自己有linux的服务器并且比较轻便一些