Home > Software design >  How can I print filled / unfilled square character using printf in c?
How can I print filled / unfilled square character using printf in c?

Time:06-30

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

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

Any help? Thank you!

CodePudding user response:

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;
}

CodePudding user response:

You can use directly like this :

#include <stdio.h>

int main()
{
  printf("■");
  return 0;
}

CodePudding user response:

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

■□

CodePudding user response:

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);
  •  Tags:  
  • c
  • Related