Home > Net >  dev-c print out a heart symbol
dev-c print out a heart symbol

Time:01-27

I'm trying to print out a heart symbol in dev-c .

To print out a heart I wrote

#include <iostream>
using namespace std;
int main()
{

    char heart = 3;

    cout << "Heart = " << heart << endl;
    
    return 0;
}

However, it doesn't print out a heart on my computer. I also changed the ANSI setting to "yes". My classmates and professor can see the heart symbol but not me :/ Can anyone help with this?

CodePudding user response:

While the ASCII code 3 is a control character, the default US Windows code page of 437 and Western European Windows code page of 850 will print Heart = ♥ in the cmd.exe window assuming the font selected supports it. This is backwards compatible with the old DOS code pages that printed symbols for some control characters. Your system may not be set to a font that supports it or it is a different code page. Use chcp to check the code page, chcp 437 to change it, and check the window's Properties page, Fonts tab. Consolas, Courier New, and Lucida Console fonts all support the heart.

C:\test>type test.cpp
#include <iostream>
using namespace std;
int main()
{
    char heart = 3;
    cout << "Heart = " << heart << endl;
    return 0;
}
C:\test>cl /nologo /EHsc /W4 test.cpp
test.cpp

C:\test>chcp
Active code page: 437

C:\test>test
Heart = ♥

Screenshot (Consolas font):

Heart = ♥

A more reliable way on Windows to output the correct character is to set the console text mode to support wide characters and output the proper Unicode character. This still requires a font that supports the Unicode character, in this case U 2665 BLACK HEART SUIT, but won't care what code page the windows supports.

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

int main () {
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wcout << L'\u2665' << std::endl;
}

CodePudding user response:

The ascii character with the code 3 is a Control Character or non-printing character, specifically it's the End-of-Text character.

These characters have special meaning and do not represent a written symbol i.e. they are not meant to be printed.

Some terminals are configured (or can be configured) to print control characters (mostly for debugging purposes). Some of these are configured to print the EoT character as ^C, others as a heart, while others as something else like or . Consult your terminal documentation to see if it can be made to print as you want.

But control characters should not be used to print symbols and should not be expected to print symbols.

If you want to print a heart symbol on the terminal you need to print an actual unicode heart symbol (e.g. U 2764 ❤) and the terminal must be configured for unicode and use a font that has that symbol.

  •  Tags:  
  • Related