命名空间
变体
操作

std::codecvt<InternT,ExternT,StateT>::length, do_length

来自 cppreference.cn
< cpp‎ | locale‎ | codecvt
 
 
 
 
 
定义于头文件 <locale>
public:

int length( StateT& state, const ExternT* from, const ExternT* from_end,

            std::size_t max ) const;
(1)
protected:

virtual int do_length( StateT& state, const ExternT* from, const ExternT* from_end,

                       std::size_t max ) const;
(2)
1) 公有成员函数,调用最派生类的成员函数 do_length
2) 尝试转换由 [fromfrom_end) 定义的字符数组中的 ExternT 字符,给定初始转换状态 state,最多转换为 maxInternT 字符,并返回这种转换将消耗的 ExternT 字符数。修改 state,如同通过为某个虚构的输出缓冲区 [toto + max) 执行 do_in(state, from, from_end, from, to, to + max, to)

目录

[编辑] 返回值

若通过 do_in() 转换,直到所有 from_end - from 字符都被消耗或产生了 maxInternT 字符,或发生转换错误,则将消耗的 ExternT 字符数。

不转换的特化 std::codecvt<char, char, std::mbstate_t> 返回 std::min(max, from_end - from)

[编辑] 示例

#include <iostream>
#include <locale>
#include <string>
 
int main()
{
    using facet_type = std::codecvt<wchar_t, char, std::mbstate_t>;
 
    // narrow multibyte encoding
    std::string s = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
              // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"
 
    std::locale loc("en_US.UTF-8");
    facet_type const& codecvt_facet = std::use_facet<facet_type>(loc);
    std::mbstate_t mb = std::mbstate_t();
    std::cout << "Only the first "
              << codecvt_facet.length(mb, s.data(), s.data() + s.size(), 2)
              << " bytes out of " << s.size() << " would be consumed"
                 " to produce the first 2 characters\n";
}

输出

Only the first 3 bytes out of 10 would be consumed to produce the first 2 characters

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 75 C++98 未指定对 state 的影响 已指定
LWG 305 C++98 std::codecvt<wchar_t, char, std::mbstate_t>::do_length
被要求返回 std::min(max, from_end - from)
未要求

[编辑] 参阅

[虚]
将字符串从 ExternT 转换为 InternT,例如从文件读取时
(虚保护成员函数) [编辑]