sprintf函數使用詳解

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).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章