std::to_chars
| 定义于头文件 <charconv>
|
||
| std::to_chars_result to_chars(char* first, char* last, /*see below*/ value, int base = 10); |
(1) | (C++17 起) |
| std::to_chars_result to_chars(char*, char*, bool, int = 10) = delete; |
(2) | (C++17 起) |
| std::to_chars_result to_chars(char* first, char* last, float value); std::to_chars_result to_chars(char* first, char* last, double value); |
(3) | (C++17 起) |
| std::to_chars_result to_chars(char* first, char* last, float value, std::chars_format fmt); |
(4) | (C++17 起) |
| std::to_chars_result to_chars(char* first, char* last, float value, std::chars_format fmt, int precision); |
(5) | (C++17 起) |
| struct to_chars_result { char* ptr; |
(6) | (C++17 起) |
通过成功填充范围 [first, last) ,转换 value 为字符串,要求 [first, last) 是合法范围。
value 以给定基底 base 转换成数位的字符串(无冗余的前导零)。范围 10..35 (含上下限)中的数字被表示成小写字母 a..z 。若值小于零,则表示以负号起始。库提供所有有符号及无符号整数和 char 类型作为参数 value 类型的重载。to_chars 拒绝 bool 类型参数,因为假如允许则结果会是 "0"/"1" 而非 "false"/"true" 。value 的差最小者,用根据 std::round_to_nearest 的舍入解决任何剩余倾向fmt 为 std::chars_format::fixed 则如同对应 printf 的转换指定为 f ,若 fmt 为 std::chars_format::scientific 则为 e ,若 fmt 为 std::chars_format::hex 则为 a (但结果无前导 "0x" ),且若 fmt 为 chars_format::general 则为 g 。precision 指定,而非以最短表示要求。std::to_chars_result 无基类或 ptr 、 ec 及隐式声明的特殊成员函数以外的成员。参数
| first, last | - | 要写入的字符范围 |
| value | - | 要转换到其字符串表示的值 |
| base | - | 使用的整数基底: 2 与 36 间的值(含上下限)。 |
| fmt | - | 使用的浮点格式, std::chars_format 类型的位掩码 |
| precision | - | 使用的浮点精度 |
返回值
成功时,返回 to_chars_result 类型的值,其 ec 等于值初始化的 std::errc ,且其 ptr 是指向被写入字符尾后一位置的指针。注意该字符串不是空终止的。
错误时,返回 to_chars_result 类型的值,它保有 std::errc::value_too_large 于 ec ,
last 于 ptr ,并于范围 [first, last) 中留下未指定状态的内容。
operator==(std::to_chars_result)
| friend bool operator==( const to_chars_result&, const to_chars_result& ) = default; |
(C++20 起) | |
检查两个参数的 ptr 与 ec 是否分别相等。
此函数对通常无限定或有限定查找不可见,而只能在 std::to_chars_result 为参数的关联类时由实参依赖查找找到。
异常
不抛出。
注解
不同于 C++ 和 C 库中的其他格式化函数, std::to_chars 是独立于本地环境、不分配、不抛出的。它只提供其他库(例如 std::sprintf )所用策略的一个小子集。它的目的是在常见的高吞吐量环境,例如基于文本的交换( JSON 或 XML )中,允许尽可能快的实现。
仅当两个函数都来自同一实现的情况下,才保证 std::from_chars 能恢复每个由 to_chars 格式化的浮点值。
若想要格式化 bool 值为 "0"/"1" ,则要求将它显式转型为另一整数类型。
示例
#include <iostream> #include <charconv> #include <system_error> #include <string_view> #include <array> int main() { std::array<char, 10> str; if(auto [p, ec] = std::to_chars(str.data(), str.data() + str.size(), 42); ec == std::errc()) std::cout << std::string_view(str.data(), p - str.data()); }
输出:
42
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| DR | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2955 | C++17 | 此函数在 <utility> 且使用 std::error_code | 移动到 <charconv> 并使用 std::errc |
| LWG 3266 | C++17 | 曾接受 bool 实参并将它提升到 int | 由被删除的重载拒绝 |
| LWG 3373 | C++17 | to_chars_result 可能拥有额外的成员
|
禁止额外的成员 |
参阅
| (C++17) |
转换字符序列到整数或浮点值 (函数) |
| (C++11) |
转换整数或浮点值为 string (函数) |
| (C++11) |
打印有格式输出到 stdout、文件流或缓冲区 (函数) |
| 插入带格式数据 ( std::basic_ostream<CharT,Traits> 的公开成员函数) |