Why doesn't putchar() output the copyright symbol while printf() does?
Asked Answered
I

2

6

So I want to print the copyright symbol and putchar() just cuts off the the most significant byte of the character which results in an unprintable character.

I am using Ubuntu MATE and the encoding I am using is en_US.UTF-8. Now what I know is that the hex value for © is 0xc2a9 and when I try putchar('©' - 0x70) it gives me 9 which has the hex value of 0x39 add 0x70 to it and you'll get 0xa9 which is the least significant byte of 0xc2a9

#include <stdio.h>

main()
{
    printf("©\n");
    putchar('©');
    putchar('\n');

}

I expect the output to be:

©
©

rather than:

©
�
Interstitial answered 17/2, 2019 at 4:38 Comment(3)
main() is not C as of 2011. Please use int main. Always use -Wall -Werror with gcc. It will tell you what's going on.Avulsion
@n.m.: main() is not C as of C99, let alone C11.Automata
@JonathanLeffler yeah my mistake, confused with gets. I always forget which version removed what.Avulsion
S
8

The putchar function takes an int argument and casts it to an unsigned char to print it. So you can't pass it a multibyte character.

You need to call putchar twice, once for each byte in the codepoint.

putchar(0xc2);
putchar(0xa9);
Sterner answered 17/2, 2019 at 4:44 Comment(0)
D
5

You could try the wide version: putwchar

Edit: That was actually more difficult than I thought. Here's what I needed to make it work:

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

int main() {
        setlocale(LC_ALL, "");
        putwchar(L'©');
        return 0;
}
Digress answered 17/2, 2019 at 4:52 Comment(1)
This is a bad idea, since mixing calls to narrow and wide functions on the same stream (stdout) has undefined behavior. Most people don't want to give up the ability to ever call printf.Girovard

© 2022 - 2024 — McMap. All rights reserved.