📜  C中的mbtowc函数

📅  最后修改于: 2021-05-25 23:45:35             🧑  作者: Mango

将多字节序列转换为宽字符。将pmb指向的多字节字符转换为wchar_t类型的值,并将其存储在pwc指向的位置。该函数返回多字节字符的长度(以字节为单位)。
mbtowc有其自己的内部移位状态,只有在调用此函数时才需要更改它。用空指针作为pmb调用函数重置状态(并返回多字节字符是否与状态有关)。
此函数的行为取决于所选C语言环境(C语言本地化库)的LC_CTYPE类别。

语法

pwc: Pointer to an object of type wchar_t.
Alternatively, this argument can be a null pointer, 
in which case the function does not store the wchar_t translation, 
but still returns the length in bytes of the multibyte character.

pmb: Pointer to the first byte of a multibyte character.
Alternatively, this argument can be a null pointer, 
in which case the function resets its internal shift 
state to the initial value and returns whether 
multibyte characters have a state-dependent encoding.

max: Maximum number of bytes of pmb 
to consider for the multibyte character.

Return Value: If the argument passed as pmb is not a null pointer, 
the size in bytes of the multibyte character pointed by pmb is returned 
when it forms a valid multibyte character and is not the terminating 
null character. If it is the terminating null character, the function 
returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed as pmb is a null pointer, 
the function returns a nonzero value if multibyte character 
encodings are state-dependent, and zero otherwise.
// C program to illustrate mbtowc
// function
#include 
#include  // function containing mbtowc & wchar_t(C) function
  
void mbtowc_func(const char* pt, size_t max)
{
    int length;
  
    // this is a typedef of an integral type
    wchar_t dest;
  
    // reset mbtowc
    mbtowc(NULL, NULL, 0);
  
    while (max > 0) {
        length = mbtowc(&dest, pt, max);
        if (length < 1) {
            break;
        }
  
        // printing each character in square braces
        printf("[%lc]", dest);
        pt += length;
        max -= length;
    }
}
  
int main()
{
    const char str[] = "geeks portal";
  
    mbtowc_func(str, sizeof(str));
  
    return 0;
}

输出:

[g][e][e][k][s][ ][p][o][r][t][a][l]
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。