名稱空間
變體
操作

std::wctomb

來自 cppreference.com
< cpp‎ | string‎ | multibyte
定義於標頭檔案 <cstdlib>
int wctomb( char* s, wchar_t wc );

將寬字元 wc 轉換為多位元組編碼,並將其(包括任何移位序列)儲存在 char 陣列中,該陣列的首個元素由 s 指向。儲存的字元數不超過 MB_CUR_MAX。轉換受當前語言環境的 LC_CTYPE 類別影響。

如果 wc 是空字元,則空位元組將寫入 s,其字首是恢復初始移位狀態所需的任何移位序列。

如果 s 是空指標,則重置全域性轉換狀態並確定是否使用移位序列。

目錄

[編輯] 引數

s - 指向字元陣列的指標,用於輸出
wc - 要轉換的寬字元

[編輯] 返回值

如果 s 不是空指標,則返回 wc 的多位元組表示中包含的位元組數;如果 wc 不是有效字元,則返回 -1

如果 s 是空指標,則將其內部轉換狀態重置為表示初始移位狀態,如果當前多位元組編碼不依賴於狀態(不使用移位序列),則返回 0;如果當前多位元組編碼依賴於狀態(使用移位序列),則返回非零值。

[編輯] 注意

每次呼叫 wctomb 都會更新內部全域性轉換狀態(一個 std::mbstate_t 型別的靜態物件,僅此函式可見)。如果多位元組編碼使用移位狀態,則此函式不可重入。在任何情況下,多個執行緒在沒有同步的情況下都不應呼叫 wctomb:可以使用 std::wcrtomb 代替。

[編輯] 示例

#include <clocale>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>
 
void print_wide(const std::wstring& wstr)
{
    bool shifts = std::wctomb(nullptr, 0); // reset the conversion state
    std::cout << "shift sequences are " << (shifts ? "" : "not" )
              << " used\n" << std::uppercase << std::setfill('0');
    for (const wchar_t wc : wstr)
    {
        std::string mb(MB_CUR_MAX, '\0');
        const int ret = std::wctomb(&mb[0], wc);
        const char* s = ret > 1 ? "s" : "";
        std::cout << "multibyte char '" << mb << "' is " << ret
                  << " byte" << s << ": [" << std::hex;
        for (int i{0}; i != ret; ++i)
        {
            const int c = 0xFF & mb[i];
            std::cout << (i ? " " : "") << std::setw(2) << c;
        }
        std::cout << "]\n" << std::dec;
    }
}
 
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    // UTF-8 narrow multibyte encoding
    std::wstring wstr = L"z\u00df\u6c34\U0001d10b"; // or L"zß水𝄋"
    print_wide(wstr);
}

輸出

shift sequences are not used
multibyte char 'z' is 1 byte: [7A]
multibyte char 'ß' is 2 bytes: [C3 9F]
multibyte char '水' is 3 bytes: [E6 B0 B4]
multibyte char '𝄋' is 4 bytes: [F0 9D 84 8B]

[編輯] 另請參閱

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