Linux中处理循环中scanf引起的缓冲区清除问题

fflush(stdin)在gcc里不能够清空缓冲区,为了解决这个问题可以用getchar()处理这个问题,如下面代码所示:

#include <stdio.h>
#define N 10 
struct student
{
    long num; 
    char name[20], sex; 
    int age, score; 
};

void main()
{
    int s,t=-1;
    long xuehao; 
    struct student stu[N]; 
    printf("Please input %d students' information as follows: \n",N);         
    printf("Num Name Sex Age Score.\n"); 
    for(s=0;s<N;s++)
    {
        printf("Please input %dth students' information:\n", s+1);
        scanf("%ld%s%c%d%d", &stu[s].num,stu[s].name,&stu[s].sex,&stu[s].age,&stu[s].score);
        while(( getchar())!='\n');
    }
    
    printf("Please input the searched students num: \n");


    scanf("%ld", &xuehao); 

    for(s=0;s<N;s++)
    {
        if(xuehao==stu[s].num)
        {
            t =s;
            break;
        }
    }
    if(t!=-1)
    {
        printf("%ld %s %c %d %d\n", stu[t].num,stu[t].name,stu[t].sex,stu[t].age,stu[t].score);

    }
    else
        printf("The searched student is not existent!") ; 
}


 

如果没有这一行,结果如下:

Please input 10 students' information as follows: 
Num Name Sex Age Score.
Please input 1th students' information:
1 wei f 1 1
Please input 2th students' information:
Please input 3th students' information:
Please input 4th students' information:
Please input 5th students' information:
Please input 6th students' information:
Please input 7th students' information:
Please input 8th students' information:
Please input 9th students' information:
Please input 10th students' information:
Please input the searched students num: 

加上这一行后输入如下:

Please input 10 students' information as follows: 
Num Name Sex Age Score.
Please input 1th students' information:
12 wei f 11 13
Please input 2th students' information:
11 weiwei f 111 34
...

 

转载于:https://www.cnblogs.com/wittfogel/p/5636967.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值