- The Microsoft compiler (embedded in visual studio) uses UTF-16 encoding to store characters, using two bytes to store one character;
- Characters are stored as integers after being saved, so using unsigned short to store Chinese characters is more appropriate; the unsigned short type happens to be two bytes long.
- GCC and LLVM/Clang compilers, however, use UTF-32 encoding and store one character using 4 bytes, so we need to use the unsigned int type for storage.
- To solve the problem of having to use different integer types to store characters because of different encodings under different compilers, Microsoft introduced the wchar_t type, whose full name is wide character type. It automatically adapts to each compiler's encoding and is automatically converted to unsigned int or unsigned short.
- The wchar_t type is located in the <wchar.h> header file. It gives code good portability, and from now on we will use it to store wide characters (what is a wide character? A character that requires more than a traditional 8-bit integer for storage).
- To use the wide-character encoding method, add the L prefix. After the L prefix is added, a character becomes a wide character; without the L prefix, ASCII encoding is used by default. Wide characters are stored using UTF-16 or UTF-32 encoding, while narrow characters are stored using ASCII encoding, as follows:
wchar_t a = L'A';
wchar_t b = L'9';
wchar_t c = L'中';
wchar_t d = L'国';
// 宽字符的输出
putchar和printf函数只能输出不加L前缀的窄字符,不能输出宽字符;
<wchar.h>中的putwchar和wprintf函数用于输出宽字符;
wprintf函数输出宽字符的格式控制符为%lc;
并且在输出宽字符之前还需要使用setlocate函数进行本地化设置,关于中文输出,参考链接:http://c.biancheng.net/view/vip_1767.html
// 宽字符串的输出
参考链接:http://c.biancheng.net/view/vip_1767.html
-
Narrow strings without the L prefix can also handle Chinese!
-
In C, only narrow characters of the char type are stored using ASCII encoding. Wide characters and wide strings of the wchar_t type are stored using UTF-16 or UTF-32 encoding, while there is no specific encoding stipulated for narrow strings of the char type. This depends on the operating system and compiler, but it is certain that modern computers no longer store narrow strings using ASCII encoding, because ASCII can display only characters such as English letters and numbers and does not support Chinese, whereas our prinf() and puts() functions can print Chinese strings!!!
-
Reference link for the encoding used to save narrow strings:
http://c.biancheng.net/view/vip_1768.html
- Today's summary:
# 字符存储编码总结:
对于char类型的窄字符,采用ASCII编码;
对于wchar_t类型的宽字符,采用UTF-16或者UTF-32编码;
对于char类型的窄字符串,微软VISUAL STUDIO使用本地编码,GCC、LLVM/Clang使用和源文件编码相同的编码;
# 另外,处理窄字符和处理宽字符使用的函数也不一样
<stdio.h>中的putchar、puts、printf函数用来处理窄字符;
<wchar.h>中的putwchar、wprintf函数用来处理宽字符;
- I did learn something today and resolved some of my previous doubts!!! Not bad, hahaha!
- This makes me even more determined to keep learning: once I master the basics of C -> advanced C and how it manages memory!!!!
Bookmarks
http://c.biancheng.net/view/1769.html