0

I am trying to print "□" and "■" using c.

I tried printf("%c", (char)254u); but it didn't work.

Any help? Thank you!

Ryan Lee
  • 37
  • 6
  • Does this answer your question? [Printing a Unicode Symbol in C](https://stackoverflow.com/questions/43834315/printing-a-unicode-symbol-in-c). You aren't that far off, but you need a bit of extra code to be able to print Unicode (really anything non-ASCII) in C – cocomac Jun 30 '22 at 03:58

4 Answers4

2

You can print Unicode characters using _setmode.

Sets the file translation mode. learn more

#include <fcntl.h>
#include <stdio.h>
#include <io.h>

int main(void) {
    _setmode(_fileno(stdout), _O_U16TEXT);
    wprintf(L"\x25A0\x25A1\n");
    return 0;
}

output

■□
Sidharth Mudgil
  • 1,293
  • 8
  • 25
1

I do not know what is (char)254u in your code. First you set locale to unicode, next you just printf it. That is it.

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

int main()
{
    setlocale(LC_CTYPE, "en_US.UTF-8");
    printf("%lc", u'□');

    return 0;
}
wohlstad
  • 12,661
  • 10
  • 26
  • 39
user14063792468
  • 839
  • 12
  • 28
  • I copied your code but, that still didn't print anything. – Ryan Lee Jun 30 '22 at 04:57
  • @RyanLee Copy code to some online editor. For example [codechef](https://www.codechef.com/ide). See that it works. If you have some non-standard system, please tag appropriate. As of now, I mark your question as not reproducible. – user14063792468 Jul 01 '22 at 07:08
  • Hmmm I guess yeah it might be my compiler problem. I am using mingw64 gcc. – Ryan Lee Jul 01 '22 at 15:59
1

You can use directly like this :

#include <stdio.h>

int main()
{
  printf("■");
  return 0;
}
embeddedstack
  • 362
  • 1
  • 13
1

As other answers have mentioned, you have need to set the proper locale to use the UTF-8 encoding, defined by the Unicode Standard. Then you can print it with %lc using any corresponding number. Here is a minimal code example:

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

int main() {
    setlocale(LC_CTYPE, "en_US.UTF-8"); // Defined proper UTF-8 locale
    printf("%lc\n", 254);               // Using '%lc' to specify wchar_t instead of char 

    return 0;
}

If you want to store it in a variable, you must use a wchar_t, which allows the number to be mapped to its Unicode symbol. This answer provides more detail.

wchar_t x = 254;
printf("%lc\n", x);