英文:
Problem with printing wide character in c
问题
你好,我想打印字母'å',它在扩展ASCII中是131,据我所知,它的UTF-8代码是00E5,UTF-16中是0x00E5。然而,在下面的代码中,程序打印出了'Õ',这不是我想要的。我不知道我做错了什么。提前谢谢。
int main(void) {
wchar_t myChar = 0x00E5;
wprintf(L"%lc", myChar);
}
英文:
Hello I want to print the letter 'å' which is 131 in extended ascii and as far as I can see has UTF-8 code 00E5 and 0x00E5 in UTF-16. However, in the code below the program prints 'Õ' which is not what I wanted. I do not know what I have done wrong. Thanks in advance.
int main(void) {
wchar_t myChar = 0x00E5;
wprintf(L"%lc", myChar);
}
答案1
得分: 4
我会尝试使用UTF-16字符字面量,并设置区域设置(setlocale
)为CP_UTF_16LE
(如果使用MSVC)或用户首选区域设置(如果不是)。
#ifdef _MSC_VER
#include <io.h> // _setmode
#include <fcntl.h> // _O_U16TEXT
#endif
#include <stdio.h>
#include <locale.h>
#include <wchar_t.h>
void set_locale_mode() {
#ifdef _MSC_VER
// Unicode UTF-16,小端字节顺序(ISO 10646的BMP)
const char *CP_UTF_16LE = ".1200";
setlocale(LC_ALL, CP_UTF_16LE);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
// 设置用户首选区域设置
setlocale(LC_ALL, "");
#endif
}
int main(void) {
set_locale_mode(); // 在任何其他输出之前执行此操作
// 使用Unicode为`å`的UTF-16字符字面量:
wchar_t myChar = u'\u00E5';
wprintf(L"%lc", myChar);
}
在Windows 11上使用VS2022进行了测试。
英文:
I'd try using an UTF-16 character literal and also set the locale (setlocale
) to CP_UTF_16LE
if using MSVC or to the user-preferred locale if not.
#ifdef _MSC_VER
#include <io.h> // _setmode
#include <fcntl.h> // _O_U16TEXT
#endif
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
void set_locale_mode() {
#ifdef _MSC_VER
// Unicode UTF-16, little endian byte order (BMP of ISO 10646)
const char *CP_UTF_16LE = ".1200";
setlocale(LC_ALL, CP_UTF_16LE);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
// set the user-preferred locale
setlocale(LC_ALL, "");
#endif
}
int main(void) {
set_locale_mode(); // do this before any other output
// UTF-16 character literal with unicode for `å`:
wchar_t myChar = u'\u00E5';
wprintf(L"%lc", myChar);
}
Tested in Windows 11 with VS2022
答案2
得分: 1
在Windows上,要输出Unicode字符,需要更改控制台模式:
#include<fcntl.h>
#include <io.h>
#include <stdio.h>
int main(void) {
_setmode(_fileno(stdout), _O_U16TEXT);
// UTF-16 character literal with unicode for `å`:
wchar_t myChar = 0x00E5;
// Adding U+20AC EURO SIGN as well.
wprintf(L"\u20ac%lc", myChar);
}
输出:
ی
英文:
On Windows, to output Unicode characters the console mode needs to be changed:
#include<fcntl.h>
#include <io.h>
#include <stdio.h>
int main(void) {
_setmode(_fileno(stdout), _O_U16TEXT);
// UTF-16 character literal with unicode for `å`:
wchar_t myChar = 0x00E5;
// Adding U+20AC EURO SIGN as well.
wprintf(L"\u20ac%lc", myChar);
}
Output:
ی
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论