【问题标题】:C++: how to convert ASCII or ANSI to UTF8 and stores in std::stringC++:如何将 ASCII 或 ANSI 转换为 UTF8 并存储在 std::string
【发布时间】:2013-12-15 01:31:50
【问题描述】:

我的公司使用如下代码:

    std::string(CT2CA(some_CString)).c_str()

我相信它将 Unicode 字符串(其类型为 CString)转换为 ANSI 编码,并且该字符串用于电子邮件的主题。但是,电子邮件的标头(包括主题)表明邮件客户端应将其解码为 un​​icode(原始代码就是这样做的)。因此,某些德语字符(如“ä ö ü”)将无法正确显示为标题。

我是否可以将此标头放回 UTF8 并存储到 std::string 或 const char* 中?

我知道有很多更聪明的方法可以做到这一点,但我需要保持代码坚持原来的方式(即将标头作为 std::string 或 const char* 发送)。

提前致谢。

【问题讨论】:

  • 你可能需要 std::wstring
  • 没有可转换为 utf8 的预编译宏。只需创建自己的,使用 CP_UTF8 调用 WideCharToMultiByte()。

标签: c++ visual-studio-2010 cstring stdstring


【解决方案1】:

这听起来像是从一种编码到另一种编码的简单转换:您可以为此使用std::codecvt<char, char, mbstate_t>。但是,我不知道您的实现是否带有合适的转换。从它的声音来看,您只需尝试将 ISO-Latin-1 转换为 Unicode。这应该很简单:前 128 个字符映射(0 到 127)与 UTF-8 相同,后半部分方便地映射到相应的 Unicode 代码点,即您只需要将相应的值编码为 UTF-8。每个字符将被两个字符替换。那它,我认为转换是这样的:

// Takes the next position and the end of a buffer as first two arguments and the
// character to convert from ISO-Latin-1 as third argument.
// Returns a pointer to end of the produced sequence.
char* iso_latin_1_to_utf8(char* buffer, char* end, unsigned char c) {
    if (c < 128) {
        if (buffer == end) { throw std::runtime_error("out of space"); }
        *buffer++ = c;
    }
    else {
        if (end - buffer < 2) { throw std::runtime_error("out of space"); }
        *buffer++ = 0xC0 | (c >> 6);
        *buffer++ = 0x80 | (c & 0x3f);
    }
    return buffer;
}

【讨论】:

  • 小心,在Windows下,ANSI表示CP-1252,这个charset看起来像iso-latin1,但又不一样……
  • @GenericAccountName:我进行了更改。感谢您的评论 - 我想我不知道。
【解决方案2】:

小心:它是'|'而不是'&'!

*buffer++ = 0xC0 | (c >> 6);
*buffer++ = 0x80 | (c & 0x3F);

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2011-04-16
    • 2011-05-22
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多