C++: Printing ASCII Heart And Diamonds With Platform Independent


Answer :

If you want a portable way, then you should use the Unicode code points (which have defined glyphs associated to them):

♠ U+2660 Black Spade Suit ♡ U+2661 White Heart Suit ♢ U+2662 White Diamond Suit ♣ U+2663 Black Club Suit ♤ U+2664 White Spade Suit ♥ U+2665 Black Heart Suit ♦ U+2666 Black Diamond Suit ♧ U+2667 White Club Suit 

Remember that everything below character 32 in ASCII is a control character. They have a meaning associated with them and you don't have a guarantee of getting a glyph or a behavior there (even though most control characters to have glyphs, although they were never intended to be printable). Still, it's not a safe bet.

However, using Unicode needs proper font and encoding support which may or may not be a problem on UNIX-likes.

On Windows at least some of the above code points map to the ASCII control character glyphs you're outputting if the console is set to raster fonts (and therefore not supporting Unicode or anything else than the currently set OEM code page). This only applies to the black variants since the white ones have no equivalent.


On Linux, you can almost always write UTF-8 to stdout and Unicode characters will be displayed beautifully.

#include <iostream>  const char heart[] = "\xe2\x99\xa5";  int main() {     std::cout << heart << '\n';     return 0; } 

You can find UTF-8 encodings of Unicode characters on sites like fileformat.info (search that page for "UTF-8 (hex)").

Another way is to use wide characters. You first need to call setlocale to set things up. Then just use wchar_t instead of char and wcout instead of cout.

#include <iostream> #include <clocale>  const wchar_t heart[] = L"\u2665";  int main() {     setlocale(LC_ALL, "");     std::wcout << heart << L'\n';     return 0; } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?