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


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


C /C++中的wcrtomb()函數將寬字符轉換為其窄的多字節表示形式。寬字符wc轉換為其等效的多字節,並存儲在s指向的數組中。該函數返回s指向的等效多字節序列的字節長度。

用法:

size_t wcrtomb( char* s, wchar_t wc, mbstate_t* ps )

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


  • s: 指定指向足以容納多字節序列的數組的指針
  • wc: 指定要轉換的寬字符。
  • ps: 指定在解釋多字節字符串時使用的轉換狀態的指針

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

  • 成功後,它將返回寫入字符數組的字節數,該字符數組的第一個元素由s指向。
  • 否則,它返回-1,並且errno設置為EILSEQ。

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

// C++ program to illustrate the 
// wcrtomb() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    setlocale(LC_ALL, "en_US.utf8"); 
  
    // initialize the string 
    wchar_t wc[] = L"z\u00df\u6c34\U0001f34c"; 
  
    // array large enough to hold a multibyte sequence 
    char s[25]; 
    int returnV; 
  
    // initial state 
    mbstate_t ps = mbstate_t(); 
    for (int i = 0; i < wcslen(wc); i++) { 
        returnV = wcrtomb(s, wc[i], &ps); 
  
        // print byte size, if its a valid character 
        if (returnV != -1) 
            cout << "Size of " << s << " is "
                 << returnV << " bytes" << endl; 
        else
            cout << "Invalid wide character" << endl; 
    } 
  
    return 0; 
}
輸出:
Size of z is 1 bytes
Size of Ã? is 2 bytes
Size of æ°´ is 3 bytes
Size of ð?? is 4 bytes

示例2:

// C++ program to illustrate the 
// wcrtomb() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    setlocale(LC_ALL, "en_US.utf8"); 
  
    // initialize the string 
    wchar_t wc[] = L"u\u00c6\u00f5\u01b5"; 
  
    // array large enough to hold a multibyte sequence 
    char s[20]; 
    int returnV; 
  
    // initial state 
    mbstate_t ps = mbstate_t(); 
    for (int i = 0; i < wcslen(wc); i++) { 
        returnV = wcrtomb(s, wc[i], &ps); 
  
        // print byte size, if its a valid character 
        if (returnV != -1) 
            cout << "Size of " << s << " is "
                 << returnV << " bytes" << endl; 
        else
            cout << "Invalid wide character" << endl; 
    } 
  
    return 0; 
}
輸出:
Size of u    Ì_e is 1 bytes
Size of Ã?Ì_e is 2 bytes
Size of õÌ_e is 2 bytes
Size of ƵÌ_e is 2 bytes


相關用法


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