gpt4 book ai didi

c++ - vswprintf 在 Mac OS X 下对某些 unicode 代码点失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:57:51 24 4
gpt4 key购买 nike

我从 vswprintf 使用 GCC 和 Mac OS X(在 Mac OS X 10.6 和 10.8 下使用 gcc 4.0 和 4.2.1 测试。Linux 下的 GCC 是受影响。Visual Studio 也受影响)。

为了演示这个问题,我对 here 中的示例进行了最低限度的改编。以便它打印出 vswprintf 的返回值:

/* vswprintf example */
#include <stdio.h>
#include <stdarg.h>
#include <wchar.h>

void PrintWide ( const wchar_t * format, ... )
{
wchar_t buffer[256];
va_list args;
va_start ( args, format );
int res = vswprintf ( buffer, 256, format, args );
wprintf ( L"result=%d\n", res );
fputws ( buffer, stdout );
va_end ( args );
}

int main ()
{
wchar_t str[] = L"test string has %d wide characters.\n";
PrintWide ( str, wcslen(str) );
return 0;
}

根据我的测试,根据 str 的值,vswprintf 有时会失败。示例:

wchar_t str[] = L"test string has %d wide characters.\n"; // works
wchar_t str[] = L"ßß® test string has %d wide characters.\n"; // works
wchar_t str[] = L"日本語 test string has %d wide characters.\n"; // FAILS
wchar_t str[] = L"Π test string has %d wide characters.\n"; // FAILS
wchar_t str[] = L"\u03A0 test string has %d wide characters.\n"; // FAILS

似乎任何包含 Unicode 代码点高于 0xff 的字符的字符串都会触发此问题。任何人都可以阐明为什么会这样吗?这似乎是一个太大的问题,以前没有注意到!

最佳答案

如果您设置了语言环境,应该没问题。要获取环境变量,您可以这样做:

setlocale(LC_CTYPE, "");   // include <locale.h>

或明确设置。这是因为所有输出函数都需要知道要使用哪种编码。

OS X 根本无法执行 vswprintf,而 Linux 运行它(尽管如果打印字符会不正确)。

这是 glibc 文档中的相关部分:

   If  the  format  string contains non-ASCII wide characters, the program
will only work correctly if the LC_CTYPE category of the current locale
at run time is the same as the LC_CTYPE category of the current locale
at compile time. This is because the wchar_t representation is plat‐
form- and locale-dependent. (The glibc represents wide characters
using their Unicode (ISO-10646) code point, but other platforms don't
do this.

关于c++ - vswprintf 在 Mac OS X 下对某些 unicode 代码点失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com