了解printf函数
基本用法
printf的作用是讲参数文本输出到屏幕。它名字里的 f 代表 format(格式化),可以制定输出文本的格式。
#include <stdio.h>
int main()
{
printf("hello world");
return 0;
}
上⾯命令会在屏幕上输出⼀⾏⽂字“HelloWorld”。
printf() 不会在⾏尾⾃动添加换⾏符,运⾏结束后,光标就停留在输出结束的地⽅,不会⾃动换 ⾏。
为了让光标移到下⼀⾏的开头,可以在输出⽂本的结尾,添加⼀个换⾏符/n。
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
printf() 是在标准库的头⽂件 stdio.h 定义的。使⽤这个函数之前,必须在源码⽂件头部引⼊这 个头⽂件。
占位符
printf() 可以在输出⽂本中指定占位符。
所谓占位符,指的是可以由其他值带入。
#include <stdio.h>
int main()
{
printf("there are %d apples\n", 3); //输出there are 3 apples
return 0;
}
上面例子中,there are %d apples\n是输出文本,而%d为占位符,这要由其他值代入。占位符第一个字符一律是%组成,第二个表示占位符的类型,%d表示这里必须代入一个整数。
所以3 代替 占位符,在屏幕上会输出 there are 3 apples。
常⽤的占位符除了 %d ,还有 %s 表⽰代⼊的是字符串。
#include <stdio.h>
int main()
{
printf("%s will go to school\n", "zhangsan"); //输出zhangsan will go to school
return 0;
}
有了上面例子的铺垫,那么我们就可以知道,zhangsan代替%s,会在屏幕上输出 zhangsan will go to school。
注意:文本中可以使用多个占位符。
输出格式
printf()可以指定占位符的格式
限定宽度
printf()允许限定占位符的最小宽度
#include <stdio.h>
int main()
{
printf("%5d\n", 123);
return 0;
}
上述例子中,在%后面加上数字指的是占位符最少要5位,如果不满5位,会在前面加上空格。
输出文本默认向右对齐,即输出内容前⾯会有空格;如果要向左对齐,要在%后面加上 - 符号。
上⾯例子中,输出内容 123 的前面添加了空格。
向左对齐:
#include <stdio.h>
int main()
{
printf("%-5dxxx\n", 123);
return 0;
}
注意:对于⼩数,这个限定符会限制所有数字的最⼩显⽰宽度。
限定⼩数位数
输出小数时,有时候需要限定小数位数时,比如要保留俩位小数时,占位符可以写成%.2f。
#include <stdio.h>
int main()
{
printf("%.2f\n", 3.134); //输出3.13
return 0;
}
这种写法可以与限定宽度占位符,结合使⽤。
#include <stdio.h>
int main()
{
printf("%6.2f\n", 3.15);
return 0;
}
上面例子中,%6.2f 表⽰输出字符串最⼩宽度为6,⼩数位数为2。所以,输出字符串的头部有两个空格。
最⼩宽度和⼩数位数这两个限定值,都可以⽤ * 代替,通过printf()的参数代入。
#include <stdio.h>
int main()
{
printf("%*.*f\n", 6,2,3.134);
return 0;
}
上⾯⽰例中, %*.*f 的两个星号通过 printf() 的两个参数 6 和 2 传⼊。
输出部分字符串
%s 占位符⽤来输出字符串,默认是全部输出。如果只想输出开头的部分,可以⽤%.[m]s 的⻓度,其中 [m] 代表⼀个数字,表⽰所要输出的⻓度。
#include <stdio.h>
int main()
{
printf("%.5s", "hello world\n"); //输出hello
return 0;
}
上⾯⽰例中,占位符 %.5s 表⽰只输出字符串“helloworld”的前5个字符,即“hello”。