Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

putchar

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:

©
�
like image 442
anas firari Avatar asked Feb 17 '19 04:02

anas firari


People also ask

What is the difference between putchar and printf?

Putchar : prints only a single character on the screen as the syntax tells. Printf : printf line or word on the screen. Hence when you want to display only one character on the screen the use putchar.

How do I print a number from Putchar?

As we know that the putchar() is used to print only characters. We can use this function to print each digit of the number. When one numeric value is passed, we have to add character '0' with it to get the ASCII form.

How does Putchar work in C?

putchar is a function in the C programming language that writes a single character to the standard output stream, stdout. Its prototype is as follows: int putchar (int character) The character to be printed is fed into the function as an argument, and if the writing is successful, the argument character is returned.

What does \b do in printf?

One common way for the backspace character to behave is by moving the cursor one position left, but not actually erasing the character in that position. The next character output will be written over it.


Video Answer


2 Answers

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);
like image 97
dbush Avatar answered Sep 23 '22 08:09

dbush


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;
}
like image 41
Zan Lynx Avatar answered Sep 21 '22 08:09

Zan Lynx