【问题标题】:How to convert a string encoded in utf16 to a string encoded in UTF-8?如何将 utf16 编码的字符串转换为 UTF-8 编码的字符串?
【发布时间】:2016-10-01 22:17:15
【问题描述】:

我有一个字符串或一个 char[],但它是用 utf-16 编码的,像这样:

现在我想将它转换为新字符串中的 utf-8,请帮助我!我已经尝试过这样的:

但是编译器告诉我我有问题。如何解决这个问题?

【问题讨论】:

  • 最好把代码写成代码,而不是用图片。另外,您能否向我们提供编译器生成的错误消息?
  • 除了@Vlad 所说的,您的代码中的data 是什么?
  • 看看这个答案stackoverflow.com/a/18597384/6345 (C++ Convert string (or char*) to wstring (or wchar_t*)) 如果它们不匹配,就适应你的类型。
  • 将编译器的问题插入到您的问题中。像“它不起作用”这样的问题需要我们一些超自然的能力。 :-)

标签: c++ string c++11 encoding utf-8


【解决方案1】:

问题很明显:您将u16_str 定义为std::string,而cvt.to_bytes() 期望std::u16string(正如变量名称所暗示的那样)。

以下代码对我有用

#include <locale>
#include <codecvt>
#include <iostream>

int main ()
 {
   std::u16string  u16_str { u"aeiuoàèìòùAEIOU" };

   std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> cvt;

   std::string  u8_str = cvt.to_bytes(u16_str);

   std::cout << u8_str << std::endl;

   return 0;
 }

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 2011-12-08
    • 2011-05-20
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多