C 庫 - mbtowc() 函式



C 的stdlib庫的mbtowc()函式用於將'str'指向的多位元組字元字串轉換為其寬字元表示形式。此函式與“mbstowcs”相同。

轉換後的字元儲存在'pwc'指向的陣列的連續元素中。

目標陣列最多隻能容納 n 個寬字元。

語法

以下是mbtowc()函式的 C 庫語法 -

int mbtowc(whcar_t *pwc, const char *str, size_t n)

引數

此函式接受以下引數 -

  • pwc - 它表示指向 wchar_t 元素陣列的指標,該陣列足夠長,可以儲存最多 n 個字元的寬字串。

  • str - 它表示指向需要轉換的空終止多位元組字串的第一個元素的指標。

  • n - 它表示'pwc'指向的陣列中存在的最大 wchar_t 字元數。

返回值

此函式返回轉換的字元數,不包括空字元。如果找到無效的多位元組字元,則返回 -1。

示例 1

在此示例中,我們建立了一個基本的 c 程式來演示mbtowc()函式的使用。

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
void mbtowc_func(const char *ptr, size_t max) {
   int length;
   wchar_t dest_arr;
   
   // Reset mbtowc internal state
   mbtowc(NULL, NULL, 0); 

   while (max > 0) {
      length = mbtowc(&dest_arr, ptr, max);
      if (length < 1) {
         break;
      }
      // Print each character in square braces
      printf("[%lc]", dest_arr); 
      ptr += length;
      max -= length;
   }
}
int main() {
   const char str[] = "tutorialspoint India";
   mbtowc_func(str, sizeof(str));
   return 0;
}

輸出

以下是輸出 -

[t][u][t][o][r][i][a][l][s][p][o][i][n][t][ ][I][n][d][i][a]

示例 2

以下 c 示例使用mbtowc()函式將多位元組字串轉換為寬字元字串。

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
int main() {
   // Set the locale to handle multibyte characters
   setlocale(LC_ALL, "");

   const char mbString[] = "This is tutorialspoint.com"; 
   wchar_t wideChar;
   
   size_t i;

   for (i = 0; i < sizeof(mbString);) {
      int length = mbtowc(&wideChar, &mbString[i], MB_CUR_MAX);
      if (length > 0) {
	     // Print each wide character in square braces
         wprintf(L"[%lc]", wideChar); 
         i += length;
      } else {
         break;
      }
   }
   return 0;
}

輸出

以下是輸出 -

[T][h][i][s][ ][i][s][ ][t][u][t][o][r][i][a][l][s][p][o][i][n][t][.][c][o][m]

示例 3

讓我們再建立一個示例,使用mbtowc()函式將無效的多位元組序列轉換為寬字元。

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

int main() {
   // Set the locale to the user's default locale
   setlocale(LC_ALL, "");

   // An invalid multibyte sequence
   const char *invalid_mb_str = "\xC3\x28";
   wchar_t ptr;
   int len;

   len = mbtowc(&ptr, invalid_mb_str, MB_CUR_MAX);

   if (len == -1) {
      printf("Invalid multibyte sequence.\n");
   } else {
      printf("Converted wide character: %lc\n", ptr);
   }
   return 0;
}

輸出

以下是輸出 -

Invalid multibyte sequence.
廣告