在 C 中,可以像这样将 unicode 字符传递给 printf():
printf("some unicode char: %c\n", "\u00B1");
但问题是在 POSIX 兼容系统上,'char' 始终是 8 位,并且大多数 UTF-8 字符(例如上面的字符)更宽并且不适合 char,因此终端上不会打印任何内容。但是,我可以这样做来实现这种效果:
printf("some unicode char: %s\n", "\u00B1");
%s 占位符自动展开,并在终端上打印一个 unicode 字符。此外,在标准中它说:
If the hexadecimal value for a universal character name is less than 0x20 or in the range 0x7F-0x9F (inclusive), or if the universal character name designates a character in the basic source character set, then the program is illformed.
当我这样做时:
printf("letter a: %c\n", "\u0061");
海湾合作委员会说:
error: \u0061 is not a valid universal character
因此这种技术也无法用于打印 ASCII 字符。在维基百科上的这篇文章中 http://en.wikipedia.org/wiki/Character_(computing)#cite_ref-3它说:
A char in the C programming language is a data type with the size of exactly one byte, which in turn is defined to be large enough to contain any member of the basic execution character set and UTF-8 code units.
但这在 POSIX 系统上可行吗?
最佳答案
在基于字节的字符串中使用通用字符取决于编译时和运行时字符编码匹配,因此除了某些情况外,这通常不是一个好主意。然而,它们在宽字符串和宽字 rune 字中工作得很好:printf("%ls", L"\u00B1");
或 printf("%lc", L'\00B1' );
将以适合您的语言环境的正确编码打印 U+00B1。
关于c - POSIX系统上通用字符有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559234/