Printing Unicode character in C

I'm trying to print the unicode star character ( 0x2605 ) in a linux terminal using C. I followed the suggested syntax of the other answers on the site, but I don't get the output:

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

int main(){

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

    return 0;
}

      

Any suggestions would be appreciated, especially how I can make this library work ncurses

.

+3
c unicode ncurses


source to share


2 answers


Two problems: first, it wchar_t

must be printed with the format %lc

, not %c

. The second is that if you don't name setlocale

, the character set will not be set correctly and you will probably get ?

your star instead. 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);
}

      

+5


source to share


If you are using stdio or ncurses, you must initialize the locale as stated in the ncurses manual . Otherwise, multibyte encodings like UTF-8 don't work.

wprintw

doesn't necessarily know about wchar_t

(although it might use the same baseline printf

, it depends on platform and configuration).



With ncurses, you can render in wchar_t

any of the following ways:

  • storing it in an array wchar_t

    and using waddwstr

    or
  • storing it in structure cchar_t

    (c setcchar

    ) and using wadd_wch

    it as a parameter, or
  • convert wchar_t

    to multibyte string and usewaddstr

+1


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics