printf()和scanf()都可以使用*修饰符来修改转换说明的含义,但他们的用法是不一样的。
当使用printf()来打印字符时,如果不想提前指定字符宽度,希望通过程序来制定,那么就可以使用*修饰符替代字段宽度。
应用时需要用一个参数告诉函数,字段宽度应该为多少。
也就是说,如果转换说明为%*d,那么参数列表中应包含*和对应的值。这个技巧对于浮点数指定精度和字符宽度同样适用。
下面给出整数类型栗子:
#include <stdio.h> int main(void) { int num = 256; int width; printf("Please input the width:\n"); scanf("%d",&width); printf("the num is |%*d|\n",width,num);//%*d旁的两个|便于观察字符长度 return 0; }程序运行结果如下:
Please input the width: 8 the num is | 256|对于浮点数的栗子如下:
#include <stdio.h> int main(void) { double weight = 242.5; int width,precision; printf("Please input the width and precision:\n"); scanf("%d %d",&width,&precision); printf("the weight is |%*.*f|\n",width,precision,weight); return 0; }运行结果如下:
Please input the width and precision: 8 3 the weight is | 242.500|scanf()中*修饰符就简单的多了,把*放在%和转换字符之间,会使得scanf()跳过相应的输入项。 示例:
#include <stdio.h> int main(void) { int a; printf("Please input three numbers:\n"); scanf("%*d %*d %d",&a); printf("the output is %d.\n",a); return 0; }运行:
Please input three numbers: 2018 2019 2020 the output is 2020.