Assigning non-ASCII characters to wide char and pr

2019-05-12 11:09发布

How can I assign non-ASCII characters to a wide char and print it to the console? This code down doesn't work:

#include <stdio.h>
int main(void)
{
    wchar_t wc = L'ć';
    printf("%lc\n", wc);
    printf("%ld\n", wc);
    return 0;
}

Output:

263
Press [Enter] to close the terminal ...

I'm using MinGW GCC on Windows 7.

3条回答
你好瞎i
2楼-- · 2019-05-12 11:13

I think your calls to printf() fail with an «Illegal byte sequence» error returned in errno, at least that is what happens here on MacOS X with the above example code (and also if using wprintf() instead of printf()). For me it works when I call setlocale(LC_ALL, ""); before the call to printf() so that it stops using the C locale by default:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main(void)
{
    wchar_t wc = L'ć';

    setlocale(LC_ALL, "");
    printf("%lc\n", wc);

    return 0;
}

It is unclear what platform/compiler you are on, so YMMV.

查看更多
家丑人穷心不美
3楼-- · 2019-05-12 11:32

You should use wprintf to print wide-character strings:

wprintf(L"%c\n", wc);
查看更多
甜甜的少女心
4楼-- · 2019-05-12 11:35

use wprintf("%lc\n" ,wc); and you will get your desired output

查看更多
登录 后发表回答