📜  C / C++中的wcrtomb()函数

📅  最后修改于: 2021-05-26 02:51:15             🧑  作者: Mango

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 
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 
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
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。