名稱空間
變體
操作

std::c32rtomb

來自 cppreference.com
< cpp‎ | string‎ | multibyte
定義於標頭檔案 <cuchar>
std::size_t c32rtomb( char* s, char32_t c32, std::mbstate_t* ps );
(C++11 起)

將 UTF-32 字元轉換為其窄多位元組表示。

如果 s 不是空指標,該函式確定儲存 c32 的多位元組字元表示所需的位元組數(包括任何移位序列,並考慮當前多位元組轉換狀態 *ps),並將多位元組字元表示儲存到以 s 指向的字元陣列的第一個元素中,根據需要更新 *ps。此函式最多可寫入 MB_CUR_MAX 位元組。

如果 s 是空指標,則此呼叫等價於 std::c32rtomb(buf, U'\0', ps),其中 buf 是某個內部緩衝區。

如果 c32 是空寬字元 U'\0',則儲存一個空位元組,其前面是恢復初始移位狀態所需的任何移位序列,並且轉換狀態引數 *ps 將更新為表示初始移位狀態。

此函式使用的多位元組編碼由當前活動的 C 語言環境指定。

目錄

[編輯] 引數

s - 指向窄字元陣列的指標,多位元組字元將儲存在此處
c32 - 要轉換的 32 位字元
ps - 指向轉換狀態物件的指標,用於解釋多位元組字串

[編輯] 返回值

成功時,返回寫入以 s 指向的字元陣列的位元組數(包括任何移位序列)。此值可能為 0,例如在處理多 char32_t 字元序列中的第一個 char32_t 時(在 UTF-32 中不會發生)。

失敗時(如果 c32 不是有效的 32 位字元),返回 -1,在 errno 中儲存 EILSEQ,並使 *ps 處於未指定狀態。

[編輯] 示例

#include <climits>
#include <clocale>
#include <cuchar>
#include <iomanip>
#include <iostream>
#include <string_view>
 
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    std::u32string_view strv = U"zß水🍌"; // or z\u00df\u6c34\U0001F34C
    std::cout << "Processing " << strv.size() << " UTF-32 code units: [ ";
    for (char32_t c : strv)
        std::cout << std::showbase << std::hex << static_cast<int>(c) << ' ';
    std::cout << "]\n";
 
    std::mbstate_t state{};
    char out[MB_LEN_MAX]{};
    for (char32_t c : strv)
    {
        std::size_t rc = std::c32rtomb(out, c, &state);
        std::cout << static_cast<int>(c) << " converted to [ ";
        if (rc != (std::size_t) - 1)
            for (unsigned char c8 : std::string_view{out, rc})
                std::cout << +c8 << ' ';
        std::cout << "]\n";
    }
}

輸出

Processing 4 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c ]
0x7a converted to [ 0x7a ]
0xdf converted to [ 0xc3 0x9f ]
0x6c34 converted to [ 0xe6 0xb0 0xb4 ]
0x1f34c converted to [ 0xf0 0x9f 0x8d 0x8c ]

[編輯] 參閱

(C++11)
將窄多位元組字元轉換為 UTF-32 編碼
(函式) [編輯]
[virtual]
將字串從 InternT 轉換為 ExternT,例如寫入檔案時
(std::codecvt<InternT,ExternT,StateT> 的虛保護成員函式) [編輯]
C 文件,關於 c32rtomb