代码之家  ›  专栏  ›  技术社区  ›  mhenry1384

swprintf阻塞8位范围以外的字符

  •  3
  • mhenry1384  · 技术社区  · 16 年前

    这种情况发生在OSX上,尽管我怀疑它适用于任何UNIX-y操作系统。

    const wchar_t *test1 = (const wchar_t *)"\x44\x00\x00\x00\x73\x00\x00\x00\x00\x00\x00\x00";
    const wchar_t *test2 = (const wchar_t *)"\x44\x00\x00\x00\x19\x20\x00\x00\x73\x00\x00\x00\x00\x00\x00\x00";
    

    在调试器中,test1看起来像“Ds”,test2看起来像“D”(带卷曲撇号)。我把这个代码叫做:

    wchar_t buf1[100], buf2[100];
    int ret1 = swprintf(buf1, 100, L"%ls", test1);
    int ret2 = swprintf(buf2, 100, L"%ls", test2);
    

    第一个swprintf调用工作正常。第二个返回-1(缓冲区不变)。

    为什么swprintf会阻塞8位范围之外的unicode字符?

    1 回复  |  直到 16 年前
        1
  •  5
  •   kennytm    16 年前

    尝试显式地将locale设置为UTF-8。

    setlocale(LC_CTYPE, "UTF-8");
    ...
    const wchar_t* test2 = L"D\x2019s";
    int ret2 = swprintf(buf2, 100, L"%ls", test2);
    ...