
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - wctomb() 函式
C 的stdlib 庫 wctomb() 函式用於將寬字元 wchar 轉換為其多位元組序列,並將其儲存在 'str' 指向的字元陣列的起始位置,並返回等效多位元組序列的位元組長度。
此函式通常用於編碼,這在處理需要支援多種語言的應用程式中的各種字元編碼時至關重要。
語法
以下是 wctomb() 函式的 C 庫語法 -
int wctomb(char *str, wchar_t wchar)
引數
此函式接受以下引數 -
str - 它表示指向陣列的指標,該陣列足夠大以容納多位元組序列,
wchar - 它表示要轉換的 wchar_t 型別的寬字元。
返回值
以下是返回值 -
如果 'str' 不為 'NULL' 且轉換成功,則其返回寫入緩衝區的位元組數。
如果 'str' 為 'NULL',則其返回 0。
如果轉換失敗,則其返回 -1。
示例 1
讓我們建立一個基本的 c 程式來演示 wctomb() 函式的使用。
#include <stdio.h> #include <stdlib.h> int main () { int i; wchar_t wchar = L'X'; char *nullstr = NULL; char *str = (char *)malloc(sizeof( char )); i = wctomb( str, wchar ); printf("Characters converted: %u\n", i); printf("Multibyte character: %.1s\n", str); printf("Trying to convert when string is NULL:\n"); i = wctomb( nullstr, wchar ); printf("Characters converted: %u\n", i); /* this will not print any value */ printf("Multibyte character: %.1s\n", nullstr); return(0); }
輸出
以下是輸出 -
Characters converted: 1 Multibyte character: X Trying to convert when string is NULL: Characters converted: 0 Multibyte character:
示例 2
以下示例使用 wctomb() 函式將寬字元轉換為多位元組字元。
#include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <locale.h> int main() { setlocale(LC_ALL, ""); // Japanese wide character to be converted wchar_t wchar = L'あ'; // Buffer to hold the multibyte character char mbstr[MB_CUR_MAX]; // Convert wide character to multibyte character int ret_val = wctomb(mbstr, wchar); // Check the return value of wctomb if (ret_val == -1) { printf("Conversion failed.\n"); } else { printf("Converted multibyte character: "); for (int i = 0; i < ret_val; ++i) { printf("%02X ", (unsigned char)mbstr[i]); } printf("\nNumber of bytes written: %d\n", ret_val); } return 0; }
輸出
以下是輸出 -
Conversion failed.
廣告