📜  C++ mbrtowc()

📅  最后修改于: 2020-09-25 09:35:28             🧑  作者: Mango

C++中的mbrtowc() 函数将一个窄的多字节字符转换为一个宽字符 (wchar_t类型)。

mbrtowc() 函数在头文件中定义。

mbrtowc()原型

size_t mbrtowc( wchar_t* pwc, const char* s, size_t n, mbstate_t* ps );

mbrtowc() 函数将s表示的多字节字符转换为宽字符 ,并存储在pwc指向的地址中。

mbrtowc()参数

mbrtowc()返回值

mbrtowc() 函数返回以下有效的第一个:

示例:mbrtowc() 函数如何工作?

#include 
#include 
#include 
using namespace std;

void test_mbrtowc(const char *s, size_t n)
{
    mbstate_t ps = mbstate_t();
    wchar_t wc;
    int retVal = mbrtowc(&wc, s, n, &ps);
    
    if (retVal == -2)
        wcout << L"Next " << n << L" byte(s) doesn't represent a complete multibyte character" << endl;
    else if (retVal == -1)
        wcout << L"Next " << n << L" byte(s) doesn't represent a valid multibyte character" << endl;
    else if (retVal == 0)
        wcout << L"The converted wide character is a null wide character" << endl;
    else
    {
        wcout << L"Next " << n << L" byte(s) hold " << retVal << L" bytes of multibyte character, ";
        wcout << L"Resulting wide character is " << wc << endl;
    }
}

int main()
{
    setlocale(LC_ALL, "en_US.utf8");
    
    char str1[] = "\u00b5";
    char str2[] = "\0";
    
    test_mbrtowc(str1, 1);
    test_mbrtowc(str1, 5);
    test_mbrtowc(str2, 5);
    
    return 0;
}

运行该程序时,输出为:

Next 1 byte(s) doesn't represent a complete multibyte character
Next 5 byte(s) hold 2 bytes of multibyte character, Resulting wide character is µ
The converted wide character is a null wide character