strfromf, strfromd, strfroml
来自cppreference.com
在标头 <stdlib.h> 定义
|
||
int strfromf( char* restrict s, size_t n, const char* restrict format, float fp ); |
(C23 起) | |
int strfromd( char* restrict s, size_t n, const char* restrict format, double fp ); |
(C23 起) | |
int strfroml( char* restrict s, size_t n, const char* restrict format, long double fp ); |
(C23 起) | |
将浮点值转换为字节字符串。
这些函数等价于 snprintf(s, n, format, fp),但格式字符串应当仅包含字符 %,可选的不包含星号 * 的精度,和以下转换指示符之一:a
、A
、e
、E
、f
、F
、g
和 G
,分别使其适用于函数后缀(而非长度修饰符)所指定的类型(double、float 或 long double)。以其他任何格式字符串调用这些函数将导致未定义行为。
参数
s | - | 指向将写入的字符串 |
n | - | 最多写入 n - 1 个字符和空终结符 |
format | - | 指向空终结字节字符串的指针,指定如何判读数据 |
fp | - | 欲转换的浮点值 |
返回值
假设 n 足够大时将会写入的字符数量,不计入终结的空字符。因而,当且仅当返回值非负且小于 n 时,才会完整写入带空终结的输出。
示例
运行此代码
#include <stdio.h> #include <stdlib.h> int main() { char buffer[32]; int written; const char* format[] = {"%a", "%A", "%e", "%E", "%f", "%F", "%g", "%G"}; for (size_t fmt = 0; fmt != sizeof format / sizeof format[0]; ++fmt) { written = strfromf(buffer, sizeof buffer, format[fmt], 3.1415f); printf("strfromf(... %s ...) = %2i, buffer: \"%s\"\n", format[fmt], written, buffer); } puts(""); for (size_t fmt = 0; fmt != sizeof format / sizeof format[0]; ++fmt) { written = strfromd(buffer, sizeof buffer, format[fmt], 3.1415); printf("strfromd(... %s ...) = %2i, buffer: \"%s\"\n", format[fmt], written, buffer); } puts(""); for (size_t fmt = 0; fmt != sizeof format / sizeof format[0]; ++fmt) { written = strfroml(buffer, sizeof buffer, format[fmt], 3.1415); printf("strfroml(... %s ...) = %2i, buffer: \"%s\"\n", format[fmt], written, buffer); } }
输出:
strfromf(... %a ...) = 13, buffer: "0x1.921cacp+1" strfromf(... %A ...) = 13, buffer: "0X1.921CACP+1" strfromf(... %e ...) = 12, buffer: "3.141500e+00" strfromf(... %E ...) = 12, buffer: "3.141500E+00" strfromf(... %f ...) = 8, buffer: "3.141500" strfromf(... %F ...) = 8, buffer: "3.141500" strfromf(... %g ...) = 6, buffer: "3.1415" strfromf(... %G ...) = 6, buffer: "3.1415" strfromd(... %a ...) = 20, buffer: "0x1.921cac083126fp+1" strfromd(... %A ...) = 20, buffer: "0X1.921CAC083126FP+1" strfromd(... %e ...) = 12, buffer: "3.141500e+00" strfromd(... %E ...) = 12, buffer: "3.141500E+00" strfromd(... %f ...) = 8, buffer: "3.141500" strfromd(... %F ...) = 8, buffer: "3.141500" strfromd(... %g ...) = 6, buffer: "3.1415" strfromd(... %G ...) = 6, buffer: "3.1415" strfroml(... %a ...) = 20, buffer: "0xc.90e5604189378p-2" strfroml(... %A ...) = 20, buffer: "0XC.90E5604189378P-2" strfroml(... %e ...) = 12, buffer: "3.141500e+00" strfroml(... %E ...) = 12, buffer: "3.141500E+00" strfroml(... %f ...) = 8, buffer: "3.141500" strfroml(... %F ...) = 8, buffer: "3.141500" strfroml(... %g ...) = 6, buffer: "3.1415" strfroml(... %G ...) = 6, buffer: "3.1415"
引用
- C23 标准(ISO/IEC 9899:2024):
- 7.24.1.3 The strfromd, strfromf, and strfroml functions
参阅
(C99)(C11)(C11)(C11)(C11) |
打印格式化输出到 stdout 、文件流或缓冲区 (函数) |
(C99)(C99) |
将字节字符串转换成浮点值 (函数) |