當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ mbrlen()用法及代碼示例


在給定當前轉換狀態ps的情況下,C /C++中的mbrlen()函數確定多字節字符的剩餘部分的大小(以字節為單位),該字符的第一個字節由str指向。此函數的行為取決於所選C語言環境的LC_CTYPE類別。

用法:

size_t mbrlen( const char* str, size_t n, mbstate_t* ps)

參數:該函數接受三個強製性參數,如下所述:


  • str: 指定指向要檢查的多字節字符串的第一個字節的指針
  • n: 指定要檢查的s中的最大字節數
  • ps: 指定指向mbstate_t對象的指針,該對象定義了轉換狀態

返回值:該函數返回四個值,如下所示:

  1. 完成有效的多字節字符的字節數
  2. 如果發生編碼錯誤,則為-1
  3. 如果s指向空字符,則為0
  4. -2如果接下來的n個字節是可能有效的多字節字符的一部分,則在檢查所有n個字節後仍不完整

以下示例程序旨在說明上述函數:
示例1:

// C++ program to illustrate 
// mbrlen() function 
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to find the size of 
// the multibyte character 
void check_(const char* str, size_t n) 
{ 
    // Multibyte conversion state 
    mbstate_t ps = mbstate_t(); 
  
    // number of byte to be saved in returnV 
    int returnV = mbrlen(str, n, &ps); 
  
    if (returnV == -2) 
        cout << "Next " << n << " byte(s) doesn't"
             << " represent a complete"
             << " multibyte character" << endl; 
  
    else if (returnV == -1) 
        cout << "Next " << n << " byte(s) doesn't "
             << "represent a valid multibyte character" << endl; 
    else
        cout << "Next " << n << " byte(s) of "
             << str << "holds " << returnV << " byte"
             << " multibyte character" << endl; 
} 
  
// Driver code 
int main() 
{ 
    setlocale(LC_ALL, "en_US.utf8"); 
    char str[] = "\u10000b5"; 
  
    // test for first 1 byte 
    check_(str, 1); 
  
    // test for first 6 byte 
    check_(str, 6); 
  
    return 0; 
}
輸出:
Next 1 byte(s) doesn't represent a complete multibyte character
Next 6 byte(s) of á??0b5holds 3 byte multibyte character

示例2:

// C++ program to illustrate 
// mbrlen() function 
// with empty string 
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to find the size of the multibyte character 
void check_(const char* str, size_t n) 
{ 
    // Multibyte conversion state 
    mbstate_t ps = mbstate_t(); 
  
    // number of byte to be saved in returnV 
    int returnV = mbrlen(str, n, &ps); 
  
    if (returnV == -2) 
        cout << "Next " << n << " byte(s) doesn't"
             << " represent a complete"
             << " multibyte character" << endl; 
  
    else if (returnV == -1) 
        cout << "Next " << n << " byte(s) doesn't "
             << "represent a valid multibyte character" << endl; 
    else
        cout << "Next " << n << " byte(s) of "
             << str << "holds " << returnV << " byte"
             << " multibyte character" << endl; 
} 
  
// Driver code 
int main() 
{ 
    setlocale(LC_ALL, "en_US.utf8"); 
    char str[] = ""; 
  
    // test for first 1 byte 
    check_(str, 1); 
  
    // test for first 3 byte 
    check_(str, 3); 
  
    return 0; 
}
輸出:
Next 1 byte(s) of holds 0 byte multibyte character
Next 3 byte(s) of holds 0 byte multibyte character


相關用法


注:本文由純淨天空篩選整理自AmanSrivastava1大神的英文原創作品 mbrlen() function in C/C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。