I'm trying to understand how does printf work with wide characters (wchar_t
).
I've made the following code samples :
Sample 1 :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
wchar_t *s;
s = (wchar_t *)malloc(sizeof(wchar_t) * 2);
s[0] = 42;
s[1] = 0;
printf("%ls\n", s);
free(s);
return (0);
}
output :
*
Everything is fine here : my character (*
) is correctly displayed.
Sample 2 :
I wanted to display an other kind of character. On my system, wchar_t
seem encoded on 4 bytes. So I tried to display the following character :
É
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
wchar_t *s;
s = (wchar_t *)malloc(sizeof(wchar_t) * 2);
s[0] = 0xC389;
s[1] = 0;
printf("%ls\n", s);
free(s);
return (0);
}
But there is no output this time, I tried with many values from the "encoding" section (cf. previous link) for s[0]
(0xC389, 201, 0xC9)... But I never get the É
character displayed. I also tried with %S
instead of %ls
.
If I try to call printf like this : printf("<%ls>\n", s)
the only character printed is '<'
, the display is truncated.
Why do I have this problem? How should I do?
scanf("%1ls")
a"É"
and report what value forprintf("%lX\n", (unsigned long) s[0])
you get. – Wendolynprintf("%ld\n", (unsigned long int) L'É');
gives me201
. – Alcottscanf("%1ls")
an "É". Your comment reports what the source code thinks a 'É' is. We are interested in how the code handles the I/O, which may differ in character encoding. – Wendolynscanf("%1ls", s);
is -1 (s[0]
not set), which supports https://mcmap.net/q/573594/-displaying-wide-chars-with-printf – Wendolyn