Home >Backend Development >C++ >How Can I Correctly Print Unicode Characters in C ?

How Can I Correctly Print Unicode Characters in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 17:58:10715browse

How Can I Correctly Print Unicode Characters in C  ?

Printing Unicode Characters in C

When attempting to print a character with a Unicode value, such as Cyrillic Small Letter Ef (U 0444), the following code may not work as expected:

int main() {
   wchar_t f = '1060';
   cout << f << endl;
}

Solution:

To print Unicode characters correctly, there are several methods:

  • Universal Character Names (UCNs):

    • The character 'ф' can be represented as 'u0444' or 'U00000444'.
  • Literal Characters (if supported by source encoding):

    • If the source code encoding supports the character, it can be written directly as 'ф'.

For terminal printing, the following code assumes compatibility between the execution encoding and the terminal emulator:

#include <iostream>

int main() {
    std::cout << "Hello, ф or \u0444!\n";
}

For Windows, setting the output file handle to UTF-16 mode is recommended:

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

int main() {
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wcout << L"Hello, \u0444!\n";
}

For portable code, the following technique can be used:

#include <iostream>
#include <vector>

int main() {
    std::vector<wchar_t> v = {0x444};
    std::wcout.write((const wchar_t*)&v[0], 1);
}

The above is the detailed content of How Can I Correctly Print Unicode Characters in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn