C 庫 - wctomb() 函式



C 的stdlibwctomb() 函式用於將寬字元 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.
廣告