c++ - Unicode 到 UTF8 的对话

标签 c++ winapi unicode utf-8

我正在尝试将 Unicode 字符串转换为 UTF8 字符串:

#include <stdio.h>
#include <string>
#include <atlconv.h>
#include <atlstr.h>

using namespace std;

CStringA ConvertUnicodeToUTF8(const CStringW& uni)
{
    if (uni.IsEmpty()) return "";
    CStringA utf8;
    int cc = 0;

    if ((cc = WideCharToMultiByte(CP_UTF8, 0, uni, -1, NULL, 0, 0, 0) - 1) > 0)
    {
        char *buf = utf8.GetBuffer(cc);
        if (buf) WideCharToMultiByte(CP_UTF8, 0, uni, -1, buf, cc, 0, 0);
        utf8.ReleaseBuffer();
    }
    return utf8;
}

int main(void)
{
    string u8str = ConvertUnicodeToUTF8(L"gökhan");

    printf("%d\n", u8str.size());

    return 0;
}

我的问题是:u8str.size() 的返回值应该是 6 吗?它现在打印 7!

最佳答案

7 是正确的。非 ASCII 字符 ö 用两个字节编码。

关于c++ - Unicode 到 UTF8 的对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815694/

相关文章:

php - 如何使用 Zend Framework 生成 _with_ utf-8 多字节字符的 pdf 文件

python - 使用 'utf-8' 编码 unicode 仅显示非 ascii 的字节字符串

c++ - 告诉 gnu-autotools 我新安装的库在哪里(使用 PKG_CONFIG?)

c++ - fatal error LNK1104 : cannot open . lib (glloaD)

c++ - BeagleBone Black 通过内核驱动中断

c++ - 关于direct3d关于D3DXCreateTextureFromFileEx的方法

c++ - 使用 C++ 在 FireFox 中获取事件选项卡 URL

c++ - 运行 Windows 程序并检测它何时以 C++ 结束

c++ - 为什么用GetDC(0)绘制图形?一旦窗口移动到它们上方就会消失?

javascript - 使用 AngularJS 在 HTML 中显示 Unicode?