Search code examples
c++unicode

is there a way to print Graphical character in CPP?


I want to print ' █ ' and ▒ to the console.

char i=177; char f=219; // ASCII for the Graphic char
 
std::cout<<i<<f;

I've tried using wchar_t and std::wcout but they aren't working. It just prints nothing or '?' or random symbols only.

Q1- Is there another way to do it ? In Visual studio it tells me to change the Unicode.

And Q2- when I use printf in Cpp it prints it . Why?


Solution

  • I ran the following code snippet on my Arch-Linux machine and it works perfectly fine. I get the full block character and the medium shade character as I expect.

    The std::locale::global-function is used to set the global locale for the entire C++ program. The global locale affects various aspects of program behavior related to localization, such as character encoding, number formatting, and date/time representations.

    In the context of setting console output to support Unicode characters, calling std::locale::global with the appropriate locale can help ensure that the console is set up to handle Unicode encoding correctly.

    #include <iostream>
    #include <locale>
    
    int main() {
        std::locale::global(std::locale("en_US.UTF-8"));
    
        wchar_t i = L'\u2588';  // Unicode for full block character '█'
        wchar_t f = L'\u2592';  // Unicode for medium shade character '▒'
    
        std::wcout << i << f << '\n';
    
        return 0;
    }
    

    As mentioned above. This works for me on Linux. Since you use CMD and Windows, I can't be sure if it'll work for you as well!

    EDIT: If it doesn't work on your end, try this: https://learn.microsoft.com/en-us/windows/console/setconsoleoutputcp#syntax