A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
printf("|%015d|\n",int_value); //右对齐,15位长度,不够补0
printf("|%15d|\n",int_value); //右对齐,15位长度,不够补空格
printf("|%-15d|\n",int_value); //左对齐,15位长度,不够补空格
printf("|%-15.2f|\n",float_value); //左对齐,15位长度,带两位小数,不够补空格
#include
int main()
{
//print char => Characters: a A
printf ("Characters: %c %c \n", 'a', 65);
// print int, long int => Decimals: 1977 650000
printf ("Decimals: %d %ld\n", 1977, 650000L);
// print int with preceding blanks or zeros => Preceding with blanks: 1977
printf ("Preceding with blanks: %10d \n", 1977);
// Preceding with zeros: 0000001977
printf ("Preceding with zeros: %010d \n", 1977);
//print int in different radices => Some different radices: 100 64 144 0x64 0144
printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
//print float => floats: 3.14 +3e+00 3.141600E+00
printf ("floats: %10.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
// print with width trick => Width trick: 10
printf ("Width trick: %*d \n", 5, 10);
// print a string, the simpliest => A string
printf ("%s \n", "A string");
return 0;
}
关于数据对齐
int main(int argc, char const *argv[])
{
//整型
printf("#####\n");//5个#
printf("%2d\n",666);
printf("%5d\n",666);//右对齐
printf("%-5d\n",666);//左对齐
//字符串
printf("#####\n");//5个#
printf("%2s\n","abc");
printf("%5s\n","abc");//右对齐
printf("%-5s\n","abc");//左对齐
//浮点数
printf("##########\n");//10个#
printf("%2f\n",6.66);
printf("%10f\n",6.66);
printf("%-10f\n",6.66);
///////////////////////////////////////////
printf("#####\n");//5个#
printf("%5.2d\n",666);
printf("%5.5d\n",666);//右对齐
printf("%5.8d\n",666);//左对齐
printf("#####\n");//5个#
printf("%5.2s\n","abc");
printf("%5.5s\n","abc");//右对齐
printf("%5.8s\n","abc");//左对齐
printf("#####\n");//5个#
printf("%5.1f\n",6.55);
printf("%5.1f\n",6.551);
printf("%5.1f\n",6.65);
printf("%5.5f\n",6.66);
return 0;
}
结果
#####
666
666
666
#####
abc
abc
abc
##########
6.660000
6.660000
6.660000
#####
666
00666
00000666
#####
ab
abc
abc
#####
6.5
6.6
6.7
6.66000
sprintf
常用来构造带变量的字符串, 比如根据参数生成的图像命名的时候最好把使用的参数值写进去.
int sprintf ( char * str, const char * format, ... );
- Write formatted data to string
/* sprintf example */
#include
int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}
Output:
[5 plus 3 is 8] is a string 13 chars long
13 = 12 个字符 + 1 个终止符 `\0`
但是sprintf
是 old C-style,不安全,比如在VS2015 中就会收到这样的警告
warning C4996: ‘sprintf’: This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h(1769): note: 参见“sprintf”的声明