【发布时间】:2017-04-10 11:40:47
【问题描述】:
我正在尝试将 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!
【问题讨论】:
-
首先,Unicode 不是一种编码方案,它是一大堆,UTF-8,UTF-16。微软可能主要为此负责,因为他们的 Unicode 是 UTF-16。但他们也叫 ASCII ANSI,其实不是。
-
@Titone 他们不调用 ASCII ANSI。 ASCII 是 7 位编码,MS 称之为 ANSI 是 8 位编码。在微软的辩护中,当他们引入 Unicode 时,世界看起来非常不同。 UTF-8 和 UTF-16 和 UTF-32 不存在。当时是UCS-2。 MS 计划使用 UTF-16 而不是 UTF-8,但它有完全合理的历史原因。