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):
Literal Characters (if supported by source encoding):
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!