C ++:如何将ASCII或ANSI转换为UTF8并存储在std :: string中

问题描述 投票:3回答:2

我的公司使用这样的代码:

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

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

无论如何,我可以将此标头放回UTF8并存储到std :: string或const char *中吗?

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

提前感谢。

c++ visual-studio-2010 cstring stdstring
2个回答
3
投票

这听起来像是从一种编码到另一种编码的普通转换:您可以为此使用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;
}

6
投票

请注意:它是'|'而不是'&'!

*buffer++ = 0xC0 | (c >> 6);
*buffer++ = 0x80 | (c & 0x3F);
© www.soinside.com 2019 - 2024. All rights reserved.