我正在尝试将 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/