mbtowc

来自cppreference.com
< c‎ | string‎ | multibyte
在标头 <stdlib.h> 定义
int mbtowc(wchar_t*          pwc, constchar*          s, size_t n )
(C99 前)
int mbtowc(wchar_t*restrict pwc, constchar*restrict s, size_t n )
(C99 起)

s 指向其首字节的多字节字符转换成宽字符,若 pwc 非空则写入 *pwc

s 为空指针,则重置全局转换状态并确定是否使用迁移序列。

目录

[编辑]注解

每次对 mbtowc 的调用更新内部全局转换状态(mbstate_t 类型的静态对象,只为此函数所知)。若多字节编码使用迁移状态,则必须留意以避免回撤或多次扫描。任何情况下,多线程不应调用 mbtowc 而不同步:可用 mbrtowc 代替。

[编辑]参数

pwc - 指向输出用宽字符的指针
s - 指向多字节字符的指针
n - s 中能被检验的字节数的限制

[编辑]返回值

s 不是空指针,则返回多字节字符所含的字节数,或若 s 所指的首字节不组成合法多字节字符则返回 -1,或若 s 指向空字符 '\0' 则返回 0

s 是空指针,则重置内部转换状态为初始迁移状态,并若当前多字节编码非状态依赖(不使用迁移序列)则返回 0,或若当前多字节编码为状态依赖(使用迁移序列)则返回非零值。

[编辑]示例

#include <locale.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <wchar.h>   // 打印多字节字符串到宽面向的 stdout// 等价于 wprintf(L"%s\n", ptr);void print_mb(constchar* ptr){ mbtowc(NULL, NULL, 0);// 重置初始转换状态constchar* end = ptr +strlen(ptr);int ret =0;for(wchar_t wc;(ret = mbtowc(&wc, ptr, end - ptr))>0; ptr += ret)wprintf(L"%lc", wc);wprintf(L"\n");}   int main(void){setlocale(LC_ALL, "en_US.utf8");// UTF-8 窄多字节编码 print_mb("z\u00df\u6c34\U0001F34C");// 即 "zß水🍌"}

输出:

zß水🍌

[编辑]引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.24.7.2 The mbtowc function (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.22.7.2 The mbtowc function (第 260 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.22.7.2 The mbtowc function (第 358 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.20.7.2 The mbtowc function (第 322 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.10.7.2 The mbtowc function

[编辑]参阅

(C95)
给定状态,转换下一个多字节字符为宽字符
(函数)[编辑]
返回下一个多字节字符的字节数
(函数)[编辑]
mbtowc 的 C++ 文档
close