今天重新翻出那本《21天学通c语言》来重学printf()这个最基本的函数,结果真的有收获。正应了《程序设计实践》里一句话,大概的意思是:没人在21天的时间里成为一门编程语言的专家。废话就说这么多吧。
函数头很简单:
int printf (char*, ...);
唯一的必要参数成为格式化字符串,也是研究的重点,大多数时间直接把要输出的字符串写在该位置,当然也可以用一个字符指针代替。
当有变量输出的时候,格式化字符串里应该包含转义字符,其格式如下:
%[flag][field_width][.[precision]][l]type
type是其中不能缺少的部分,含义见表:
| type | Output | Example |
|
| Character | a |
|
| Signed decimal integer | 392 |
|
| Scientific notation (mantise/exponent) using e character | 3.9265e2 |
|
| Scientific notation (mantise/exponent) using E character | 3.9265E2 |
|
| Decimal floating point | 392.65 |
|
| Use shorter %e or %f | 392.65 |
|
| Use shorter %E or %f | 392.65 |
|
| Signed octal | 610 |
|
| String of characters | sample |
|
| Unsigned decimal integer | 7235 |
|
| Unsigned hexadecimal integer | 7fa |
|
| Unsigned hexadecimal integer (capital letters) | 7FA |
|
| Address pointed by the argument | B800:0000 |
|
| Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored. |
在转换字符前面加 l 可以把输出类型转换成long或者double。
[field_width][.[precision]]限定的是字段宽度和精度,例如:
///////////////////////////////////////////////////
float pi=3.1415926;
printf("limited:%8.1f",pi);
////////////////输出如下////////////////////
limited: 3.1
///////////////////////////////////////////////////
默认的情况下限制宽度的输出是右对齐的,如果在这里写一个 * ,那么可以在输出的参数前面加上一个整数来限制宽度(如果没有精度限制就不管用,至少我测试的结果是这样)。
//////////////////////////////////////////////////
int i=10;
float pi=3.14159;
printf ("output:%*.2f/n",i,pi);
/////////////////////输出/////////////////////
output: 3.14
/////////////////////////////////////////////////
[flag]有四种值:
1 + 在数字前面加上正或负号。
2 - 使输出左对齐。
3 空格 在整数前面加空格(用于和负数对齐)。
4 # 只能用于转换字符x、X或o。表示在非零八(十六)进制数加上0X、0x (对应x和X),或0(对应o)。
格式化字符串中还有一些特殊字符是不能直接写在里面的,这就需要用到转义序列,常用的几个:
/n换行 /b回退符 /n水平制表符(tab) //反斜扛 /?问号 /'单引号 /"双引号
学c,还是要有一点耐心的。
参考信息:
http://www.cplusplus.com/ref/cstdio/printf.html
ruturn 0;
博主重新学习《21天学通C语言》中printf()函数有了新收获。介绍了printf()函数头,格式化字符串是重点,包含转义字符,说明了type、[field_width][.[precision]]、[flag]的作用,还提及格式化字符串中的转义序列,强调学C语言要有耐心。
2735

被折叠的 条评论
为什么被折叠?



