C语言笔记4--*的作用

C语言的输入输出涵盖了非常巨大的知识面,这里结合输入输出写一下*的作用。
1.printf中作为控制宽度输出

#define _CRT_SECURE_NO_WARNINGS//安全问题
#include<stdio.h>
#include<stdlib.h>
void main()
{
    int a=1234;
    int b=10;
    printf("%*d\n",b,a);
    system("pause");
}

从打印结果可以看出,b的值传给了*,控制输出的宽度。
2.scanf中起到忽略、跳过的作用

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void main()
{
    int a;
    scanf("%*5d%d",&a);
    printf("a=%d",a);
    system("pause");
}

输入123456;打印a=6;
输入1234567;打印a=67;
也就是说*代表的是忽略,*的数字5代表忽略的宽度
3.利用*和sscanf函数进行简单的数据处理

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
    char info[100]="123,某某某,男,20,170,12345678912";//编号、姓名、性别、年龄、身高、电话
    char name[20];
    int age,height;
    long long tel_num;//电话需要用长长整型
    //把,改为空格作为字符串的结束标志,不然会出错
    for (int i = 0; i < strlen(info); i++)
    {
        if (info[i] == ',')
        {
            info[i] = ' ';
        }
    }
    sscanf(info,"%*d %s %*s %d %d %lld",name,&age,&height,&tel_num);//sscanf要严格按照格式输入
    printf("name=%s\nage=%d\nheight=%d\ntel_num=%lld",name,age,height,tel_num);
    system("pause");
}

运行结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40850689/article/details/81912407
4--