std::to_chars_C++中文网
| 定义于头文件 |
||
| std::to_chars_result to_chars(char* first, char* last, |
(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) 是合法范围。
1) 整数格式化函数: value 以给定基底 base 转换成数位的字符串(无冗余的前导零)。范围 10..35 (含上下限)中的数字被表示成小写字母 a..z 。若值小于零,则表示以负号起始。库提供所有有符号及无符号整数和 char 类型作为参数 value 类型的重载。
2) bool 的重载被删除。 to_chars 拒绝 bool 类型参数,因为假如允许则结果会是 "0"/"1" 而非 "false"/"true" 。
3) 如同用 std::sprintf 于默认( "C" )本地环境转换值为字符串。转换指定符是 f 或 e ,根据最短表示方式的要求选择(两者相当时优先选择 f ):字符串表示由小数点(若存在)前至少有一位,且用对应的 std::from_chars 分析该表示能准确恢复值的,最小数量的字符组成。若有数个这种表示,则选择到 value 的差最小者,用根据 std::round_to_nearest 的舍入解决任何剩余倾向
5) 同 (4) ,除了精度以参数 precision 指定,而非以最短表示要求。
6) 返回类型(见后述返回值)
参数
| 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()); }
输出:
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| DR | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2955 | C++17 | 此函数在 <utility> 且使用 std::error_code | 移动到 <charconv> 并使用 std::errc |
| LWG 3266 | C++17 | 曾接受 bool 实参并将它提升到 int | 由被删除的重载拒绝 |