C语言 如何初始化 wchar_t 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12996062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:11:16  来源:igfitidea点击:

How to initialize a wchar_t variable?

cgccunicodewchar-t

提问by Yishu Fang

I am reading the book: C: In a Nutshell, and after reading the section Character Sets, which talks about wide characters, I wrote this program:

我正在阅读这本书:C: In a Nutshell,在阅读了讨论宽字符的Character Sets部分后,我编写了这个程序:

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

int main() {
  wchar_t wc = '\x3b1';
  wprintf(L"%lc\n", wc);
  return 0;
}

I then compiled it using gcc, but gcc gave me this warning:

然后我使用 gcc 编译它,但是 gcc 给了我这个警告:

main.c:7:15: warning: hex escape sequence out of range [enabled by default]

main.c:7:15: 警告:十六进制转义序列超出范围 [默认启用]

And the program does not output the character α (whose unicode is U+03B1), which is what I wanted it to do.

并且程序不输出字符α(其unicode为U+03B1),这正是我想要它做的。

How do I change the program to print the character α?

如何更改程序以打印字符 α?

采纳答案by David Ranieri

This works for me

这对我有用

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

int main(void) {
  wchar_t wc = L'\x3b1';

  setlocale(LC_ALL, "en_US.UTF-8");
  wprintf(L"%lc\n", wc);
  return 0;
}

回答by David Heffernan

wchar_t wc = L'\x3b1';

is the correct way to initialise a wchar_t variable to U+03B1. The L prefix is used to specify a wchar_t literal. Your code defines a char literal and that's why the compiler is warning.

是将 wchar_t 变量初始化为 U+03B1 的正确方法。L 前缀用于指定 wchar_t 文字。您的代码定义了一个字符文字,这就是编译器发出警告的原因。

The fact that you don't see the desired character when printing is down to your local environment's console settings.

打印时看不到所需字符的事实取决于本地环境的控制台设置。

回答by Aniket Inge

try L'\x03B1'It might just solve your problem. IF you're in doubt you can try :

尝试L'\x03B1'它可能只是解决您的问题。如果您有疑问,可以尝试:

'\u03b1' to initialize.