名稱空間
變體
操作

std::mbrtowc

來自 cppreference.com
在標頭檔案 <cwchar> 中定義
std::size_t mbrtowc( wchar_t* pwc,

                     const char* s,
                     std::size_t n,

                     std::mbstate_t* ps );

將窄多位元組字元轉換為寬字元。

如果 s 不是空指標,則檢查多位元組字元字串的最多 n 個位元組,從 s 指向的位元組開始,以確定完成下一個多位元組字元所需的位元組數(包括任何移位序列)。如果函式確定 s 中的下一個多位元組字元是完整且有效的,則將其轉換為相應的寬字元並存儲在 *pwc 中(如果 pwc 不是空)。

如果 s 是空指標,則忽略 npwc 的值,並且呼叫等效於 std::mbrtowc(nullptr, "", 1, ps)

如果生成的寬字元是空字元,則儲存在 *ps 中的轉換狀態是初始移位狀態。

目錄

[編輯] 引數

pwc - 指向將寫入結果寬字元的位置的指標
s - 指向用作輸入的多位元組字元字串的指標
n - s 中可檢查的位元組數的限制
ps - 指向解釋多位元組字串時使用的轉換狀態的指標

[編輯] 返回值

以下適用情況中的第一個

  • 0 如果從 s 轉換的字元(如果非空則儲存在 pwc 中)是空字元。
  • 成功從 s 轉換的多位元組字元的位元組數 [1...n]
  • static_cast<std::size_t>(-2) 如果接下來的 n 個位元組構成一個不完整但目前有效的多位元組字元。不會向 *pwc 寫入任何內容。
  • static_cast<std::size_t>(-1) 如果發生編碼錯誤。不會向 *pwc 寫入任何內容,值 EILSEQ 儲存在 errno 中,*ps 的值未指定。

[編輯] 示例

#include <clocale>
#include <cstring>
#include <cwchar>
#include <iostream>
 
void print_mb(const char* ptr)
{
    std::mbstate_t state = std::mbstate_t(); // initial state
    const char* end = ptr + std::strlen(ptr);
    int len;
    wchar_t wc;
    while ((len = std::mbrtowc(&wc, ptr, end-ptr, &state)) > 0)
    {
        std::wcout << "Next " << len << " bytes are the character " << wc << '\n';
        ptr += len;
    }
}
 
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    // UTF-8 narrow multibyte encoding
    const char* str = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
                      // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
    print_mb(str);
}

輸出

Next 1 bytes are the character z
Next 2 bytes are the character ß
Next 3 bytes are the character 水
Next 4 bytes are the character 𝄋

[編輯] 參閱

將下一個多位元組字元轉換為寬字元
(函式) [編輯]
將寬字元轉換為其多位元組表示,給定狀態
(函式) [編輯]
[virtual] (虛擬函式)
將字串從 ExternT 轉換為 InternT,例如從檔案讀取時
(std::codecvt<InternT,ExternT,StateT> 的虛保護成員函式) [編輯]
C 文件 關於 mbrtowc