Home >Backend Development >C++ >How Can I Successfully Print Unicode Characters in C ?
Printing Unicode Characters in C
Attempting to print a Unicode character, such as the Russian Cyrillic letter "ф" (U 0444), can be challenging in C . This article explores how to successfully print Unicode characters using C methods.
Using Universal Character Names (UCNs)
The most straightforward method is to use Universal Character Names (UCNs). For instance, the character "ф" has a Unicode value of U 0444. In C , you can represent this as "u0444" or "U00000444".
int main() { wchar_t f = '\u0444'; cout << f << endl; }
Using Encodings
If your source code encoding supports the desired character, you can use it directly in your code. For example, in UTF-8 encoding, the character "ф" is 'u0444'.
char b = '\u0444';
Printing to Terminal Emulators
Printing Unicode characters to a terminal emulator depends on the emulator's encoding and compatibility with the compiler's execution encoding. If they match, using std::cout is sufficient.
int main() { std::cout << "Hello, ф or \u0444!\n"; }
Handling Windows Specifics
Working with Windows requires additional considerations. One approach is to set the output file handle to UTF-16 using _setmode().
#include <iostream> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); std::wcout << L"Hello, \u0444!\n"; }
Alternatively, for portability, you can use wide strings (wchar_t) and write to the wide stream (std::wcout) directly.
int main() { wchar_t f = L'\u0444'; // Prepend L to denote wide char literal wcout << f << endl; }
The above is the detailed content of How Can I Successfully Print Unicode Characters in C ?. For more information, please follow other related articles on the PHP Chinese website!