C编程,unicode和linux终端

use*_*542 3 c linux unicode command-line

所以我要做的是使用C和宽字符将日文字符写入终端屏幕.

问题是我正在做什么,以便我可以解决它,我在使用宽字符时应该注意什么其他警告,你对我正在尝试做什么有任何其他评论吗?




坏代码:

#include <stdio.h>
#include <wchar.h>

int main( ) {
    wprintf(L"%c\n", L"\x3074");
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,但我想知道原因.


当我尝试使用wchar_t来保存值时,问题只会变得更糟:

wchar_t pi_0 = 0x3074;      // prints a "t" when used with wprintf
wchar_t pi_1 = "\x3074";    // gives compile time warning
wchar_t pi_2 = L"\x3074";   // gives compile time warning
Run Code Online (Sandbox Code Playgroud)

所以我也想做这个工作,因为我打算让数据结构保存这些字符的字符串.




谢谢!

ken*_*ytm 10

该类型的"\x3074"IS const char[]和类型L"\x3074"const wchar_t[].

如果您需要wchar_t,请使用单引号:

L'\x3074'
Run Code Online (Sandbox Code Playgroud)

%c打印一个char,但wchar_t你需要一个%lc.


APr*_*mer 5

代码中至少有两个问题。

  • 肯尼指出了第一个,格式与参数不匹配
  • 第二个是您错过了对 setlocale() 的调用

(还有一个假设是宽字符集是 Unicode——我似乎记得 Linux 总是如此,但它不是通用的)。

在正确配置的终端中,

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main( ) {
    setlocale(LC_ALL, "");
    wprintf(L"%ls\n", L"\x0152\x3074");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

应该管用。如果没有,我将首先检查 setlocale() 和 wprint() 的结果。

(我添加了 U+0152,它是 OE 连字,以便我可以检查行为;我没有使用带有 U+3074 的字体)