5

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:

©
�
codeforester
  • 39,467
  • 16
  • 112
  • 140

2 Answers2

7

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);
dbush
  • 205,898
  • 23
  • 218
  • 273
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;
}
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • 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. – R.. GitHub STOP HELPING ICE Feb 17 '19 at 14:38