3 questions on wchar_t

A

arnuld

int main(void)
{
wchar_t a = 'a';

char my_a = a;

printf("wchar_t a = %c\n", a);
printf("char my_a = %c\n", my_a);


return 0;
}

============== OUTPUT ==============
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra test.c
test.c: In function `main':
test.c:13: warning: int format, wchar_t arg (arg 2)
[arnuld@dune programs]$




I have 3 questions:

is it safe, when I am sure thar wchar_t holds only normal alphanumeric
characters like a-z, A-Z and 0-9 ??

is there a way to print wchar strings

is there a way to convert a wchar_t to char ?
 
H

Harald van Dijk

int main(void)
{
wchar_t a = 'a';

You should assign L'a'. It need not have the same numeric value as 'a'.
char my_a = a;

You should assign 'a' instead of relying on an implicit wchar_t->char
conversion, which won't always do the right thing.
printf("wchar_t a = %c\n", a);
printf("char my_a = %c\n", my_a);


return 0;
}

============== OUTPUT ==============
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra test.c
test.c: In function `main':
test.c:13: warning: int format, wchar_t arg (arg 2) [arnuld@dune
programs]$




I have 3 questions:

is it safe, when I am sure thar wchar_t holds only normal alphanumeric
characters like a-z, A-Z and 0-9 ??

No, for the same reason that

printf("%d\n", 0L);

is not safe even though 0L is in range for an int.
is there a way to print wchar strings

Yes. %lc and %ls print wint_t and wchar_t[] values. For a single wchar_t,
cast it to wint_t and use %lc.
is there a way to convert a wchar_t to char ?

wctob can do that. It will either give you a valid result in the range of
unsigned char -- convert that to char if you like -- or it will give you
EOF if the character would take up more than one byte.
 
M

Mark Wooding

arnuld said:
is it safe, when I am sure thar wchar_t holds only normal alphanumeric
characters like a-z, A-Z and 0-9 ??
No.

is there a way to print wchar strings

A `%ls' conversion specifier to `printf' and chums; `fputws', if your
output file has the appropriate orientation.
is there a way to convert a wchar_t to char ?

`wctob' or `wcrtomb'. Or you can mess around with `wctomb' if you don't
have other threads to worry about.

-- [mdw]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top