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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
...

 

以上是关于Linux中处理循环中scanf引起的缓冲区清除问题的主要内容,如果未能解决你的问题,请参考以下文章

scanf陷阱--缓冲区引起的跳过输入问题,以及还有scanf,getchar 和gets的爱恨情仇

c语言:关于scanf()语句与while循环的问题

在while循环中使用scanf进行无限循环

Linux系统清除缓存

scanfgetsgetcharcincin.getcin.getlinegetline总结

Scanf未在C中执行[重复]