printf()和scanf()中的%*d用法

printf()和scanf()都可以使用*修饰符来修改转换说明的含义,但他们的用法是不一样的。

一、printf()中的*修饰符

当使用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;
}

其实就是相当于把width的值拷贝给了%*d中的*。

程序运行结果如下:

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;
}

这里相当于把width的值拷贝给%*.*f的第一个*,precision的值拷贝给其中的第二个*。

运行结果如下:

Please input the width and precision:
8 3
the weight is | 242.500|

二、scanf()中的*修饰符

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;
}

这里的scanf()中,直接跳过两个整数,把第三个整数拷贝给a。

运行:

Please input three numbers:
2018 2019 2020
the output is 2020.

猜你喜欢

转载自blog.csdn.net/Dscerpor_/article/details/107060121