tips:
1.函数包含在stdio.h文件中,使用#include<stdio.h>
2.函数声明:int sprintf( char *buffer, const char *format , [argument,...] );
3.主要功能是根据char *format定义格式输出到字符串缓冲区buffer
sprintf主要是依靠控制格式的字符串const char *format 来完成灵活的写入
format的用法跟printf函数的一样,下面介绍printf的format结构
format的结构 %[flags][width][.precision][length]specifier
1.specifier
specifier | Output | Example |
---|---|---|
d or i | Signed decimal integer | 392 |
u | Unsigned decimal integer | 7235 |
o | Unsigned octal | 610 |
x | Unsigned hexadecimal integer | 7fa |
X | Unsigned hexadecimal integer (uppercase) | 7FA |
f | Decimal floating point, lowercase | 392.65 |
F | Decimal floating point, uppercase | 392.65 |
e | Scientific notation (mantissa/exponent), lowercase | 3.9265e+2 |
E | Scientific notation (mantissa/exponent), uppercase | 3.9265E+2 |
g | Use the shortest representation: %e or %f | 392.65 |
G | Use the shortest representation: %E or %F | 392.65 |
a | Hexadecimal floating point, lowercase | -0xc.90fep-2 |
A | Hexadecimal floating point, uppercase | -0XC.90FEP-2 |
c | Character | a |
s | String of characters | sample |
p | Pointer address | b8000000 |
n | Nothing printed. The corresponding argument must be a pointer to a signed int.The number of characters written so far is stored in the pointed location. | |
% | A % followed by another % character will write a single % to the stream. | % |
2.flags
flags | description |
---|---|
- | Left-justify within the given field width; Right |
+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space) If no sign is going to be written, a blank space is inserted before the value.
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero.
Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0 Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).