在C++中将UTF-8转换为ANSI

Dam*_*ian 2 c++ ascii utf-8 character-encoding

我无法在任何地方找到这个问题的答案.

如何在C++中将字符串从UTF-8转换为ANSI(扩展ASCII)?

Die*_*Epp 6

通常,人们使用libiconv(网页),它是可移植的并且可以在大多数平台上运行.正如KerrekSB所提到的,如果你将字符集视为"扩展ASCII",你会遇到很大麻烦 - 我确信至少有一百个字符集可以被称为"扩展ASCII",包括UTF-8.

此外,请确保您知道所需的编码:ISO-8859-1或CP1252.Windows版本用其他打印字符替换C1控制代码.


KIM*_*oon 6

仅限 Windows:

string UTF8ToANSI(string s)
{
    BSTR    bstrWide;
    char*   pszAnsi;
    int     nLength;
    const char *pszCode = s.c_str();

    nLength = MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, NULL, NULL);
    bstrWide = SysAllocStringLen(NULL, nLength);

    MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, bstrWide, nLength);

    nLength = WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, NULL, 0, NULL, NULL);
    pszAnsi = new char[nLength];

    WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, pszAnsi, nLength, NULL, NULL);
    SysFreeString(bstrWide);

    string r(pszAnsi);
    delete[] pszAnsi;
    return r;
}
Run Code Online (Sandbox Code Playgroud)