Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a Unicode Symbol in C

Tags:

c

unicode

ncurses

I'm trying to print a unicode star character (0x2605) in a linux terminal using C. I've followed the syntax suggested by other answers on the site, but I'm not getting an output:

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

int main(){

    wchar_t star = 0x2605;
    wprintf(L"%c\n", star);

    return 0;
}

I'd appreciate any suggestions, especially how I can make this work with the ncurses library.

like image 574
Luke Collins Avatar asked May 07 '17 17:05

Luke Collins


People also ask

How do I print Unicode?

We can put the Unicode value with the prefix \u. Thus we can successfully print the Unicode character.

What is the Unicode code for C?

Unicode Character “C” (U+0043)

Does C use Ascii or Unicode?

As far as I know, the standard C's char data type is ASCII, 1 byte (8 bits).


2 Answers

Two problems: first of all, a wchar_t must be printed with %lc format, not %c. The second one is that unless you call setlocale the character set is not set properly, and you probably get ? instead of your star. The following code seems to work though:

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

int main() {
    setlocale(LC_CTYPE, "");
    wchar_t star = 0x2605;
    wprintf(L"%lc\n", star);
}

And for ncurses, just initialize the locale before the call to initscr.


Whether you are using stdio or ncurses, you have to initialize the locale, as noted in the ncurses manual. Otherwise, multibyte encodings such as UTF-8 do not work.

wprintw doesn't necessarily know about wchar_t (though it may use the same underlying printf, this depends on the platform and configuration).

With ncurses, you would display a wchar_t in any of these ways:

  • storing it in an array of wchar_t, and using waddwstr, or
  • storing it in a cchar_t structure (with setcchar), and using wadd_wch with that as a parameter, or
  • converting the wchar_t to a multibyte string, and using waddstr
like image 41
Thomas Dickey Avatar answered Oct 13 '22 00:10

Thomas Dickey