3

我在vswprintf使用 GCC 和 Mac OS X(在 Mac OS X 10.6 和 10.8 下使用 gcc 4.0 和 4.2.1 测试。Linux 下的 GCC不受影响。Visual Studio 也不受影响)时遇到了莫名其妙的故障(返回值 -1 )。

为了演示这个问题,我对此处的示例进行了最低限度的修改,以便打印出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;
}

从我的测试看来,根据 的值strvswprintf有时会失败。例子:

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都会触发此问题。任何人都可以解释为什么会这样吗?这似乎是一个太大的问题,以前没有注意到!

4

1 回答 1

0

如果你设置了语言环境,它应该没问题。要获取环境变量,您可以执行以下操作:

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.
于 2013-03-15T19:15:39.963 回答