C++ - Printing copyright symbol © displays reversed not sign ¬

With a simple solution.


The console application below prints a simple copyright message. Instead of displaying the copyright symbol © however, it prints the reversed not sign ¬. Why is this?


  int main()
  {
      char* copyright = "Copyright ©\r\n";
      printf(copyright);
      return 0;
  }
  

Program output:

  Copyright ⌐   

Your text editor is likely using one of the following character encodings: Unicode (usually UTF-8), ISO-8859-1, or Windows CP-1252.
Unicode is based on ISO-8859-1, which is itself based on Windows CodePage 1252, which is why they are all similar.

In all of these character encodings, the copyright symbol is encoded as: hex A9, Octal 169, or Decimal 251.

The default CodePage for a console application is 437.
And in CodePage 437, the character at hex A9 / Octal 169 is ¬. The reversed not sign.
CodePage 437 has no copyright symbol.


And that's the problem. Your text editor is using one encoding, an encoding that does support the copyright symbol, and the console is using a different encoding. One that does not support the copyright symbol.


We can confirm this by modifying the program to print the active CodePage.


  int main()
  {
      auto cp = GetConsoleOutputCP();
      printf("Current codepage is %d\r\n", cp);
 
      char* copyright = "Copyright ©\r\n";
      printf(copyright);
      return 0;
  }
  

Program output:

  Current codepage is 437
  Copyright ⌐
  

CodePage 437 is designed for DOS console applications, which is why it has 48 characters for drawing lines and blocks.


We can fix the problem by changing the console CodePage to 1252:


  int main()
  {
      SetConsoleOutputCP(1252);
 
      auto cp = GetConsoleOutputCP();
      printf("Current codepage is %d\r\n", cp);
 
      char* copyright = "Copyright ©\r\n";
      printf(copyright);
      return 0;
  }
  

Program output:

  Current codepage is 1252
  Copyright ©
  

Alternative fix #1. Write Unicode to the console using _setmode(_O_U16TEXT) and wprintf():


  int main()
  {
      _setmode(_fileno(stdout), _O_U16TEXT);
      
      wchar_t* copyright = L"Copyright ©\r\n";
      wprintf(copyright);
      return 0;
  }
  

Program output:

  Copyright ©
  

Alternative fix #2. Write Unicode to the console using WriteConsoleW():


  int main()
  {
      wchar_t* copyright = L"Copyright ©\r\n";
      auto handle = GetStdHandle(STD_OUTPUT_HANDLE);
      WriteConsoleW(handle, copyright, wcslen(copyright), NULL, NULL);
      return 0;
  }
  

Program output:

  Copyright ©
  

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath