gpt4 book ai didi

c - 将 wchar 打印到 Linux 控制台?

转载 作者:IT王子 更新时间:2023-10-29 00:16:17 25 4
gpt4 key购买 nike

我的C程序贴在下面。在 bash 中,程序打印“char is”,Ω未打印。我的语言环境都是 en_US.utf8。

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

int main() {
int r;
wchar_t myChar1 = L'Ω';
r = wprintf(L"char is %c\n", myChar1);
}

最佳答案

这很有趣。显然,编译器将 omega 从 UTF-8 转换为 UNICODE,但 libc 以某种方式将其搞砸了。

首先:%c 格式说明符需要一个 char(即使在 wprintf 版本中)所以您必须指定 %lc (因此 %ls 用于字符串)。

其次,如果您像这样运行代码,语言环境设置为 C(它不会自动从环境中获取)。你必须调用setlocale用一个空字符串从环境中获取语言环境,所以 libc 又开心了。

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

int main() {
int r;
wchar_t myChar1 = L'Ω';
setlocale(LC_CTYPE, "");
r = wprintf(L"char is %lc (%x)\n", myChar1, myChar1);
}

关于c - 将 wchar 打印到 Linux 控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7695592/

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