wctob

来自cppreference.com
< c‎ | string‎ | multibyte
在标头 <wchar.h> 定义
int wctob( wint_t c );
(C95 起)

若宽字符 c 在初始迁移状态的多字节字符等价物为单个字节,则窄化它。

这典型地对来自 ASCII 字符集的字符可行,因为大多数多字节编码(如 UTF-8)用单字节编码这些字符。

参数

c-要窄化的宽字符

返回值

c 不表示在初始迁移状态长度为 1 的多字节字符,则返回 EOF

否则,返回 c 作为 unsigned char 的单字节表示,并转换为 int

示例

#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <assert.h>
 
void try_narrowing(wchar_t c)
{
    int cn = wctob(c);
    if(cn != EOF)
        printf("%#x 窄化为 %#x\n", c, cn);
    else
        printf("%#x 无法窄化\n", c);
}
 
int main(void)
{
    char* utf_locale_present = setlocale(LC_ALL, "th_TH.utf8");
    assert(utf_locale_present);
    puts("Thai UTF-8 locale 中:");
    try_narrowing(L'a');
    try_narrowing(L'๛');
 
    char* tis_locale_present = setlocale(LC_ALL, "th_TH.tis620");
    assert(tis_locale_present);
    puts("Thai TIS-620 locale 中:");
    try_narrowing(L'a');
    try_narrowing(L'๛');
}

可能的输出:

Thai UTF-8 locale 中:
0x61 窄化为 0x61
0xe5b 无法窄化
Thai TIS-620 locale 中:
0x61 窄化为 0x61
0xe5b 窄化为 0xfb

引用

  • C11 标准(ISO/IEC 9899:2011):
  • 7.29.6.1.2 The wctob function (第 441 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.24.6.1.2 The wctob function (第 387 页)

参阅

(C95)
若可能,加宽单字节窄字符为宽字符
(函数)
wctob 的 C++ 文档