Ryan Lee
Ryan Lee

Reputation: 57

How can I print filled / unfilled square character using printf in c?

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

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

Any help? Thank you!

Upvotes: 0

Views: 846

Answers (4)

jacksonn-gtc
jacksonn-gtc

Reputation: 36

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

Upvotes: 1

Sidharth Mudgil
Sidharth Mudgil

Reputation: 1461

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

■□

Upvotes: 2

embeddedstack
embeddedstack

Reputation: 387

You can use directly like this :

#include <stdio.h>

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

Upvotes: 1

user14063792468
user14063792468

Reputation: 956

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

Upvotes: 1

Related Questions