码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2016-07-03 11:49:40      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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
...

 

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

标签:

原文地址:http://www.cnblogs.com/wittfogel/p/5636967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!