帮我看看这个程序有哪里有问题(C语言)

来源:百度知道 编辑:UC知道 时间:2024/05/14 12:30:38
#define N 5
struct student
{
int num;
char name[20];
float score1;
float score2;
float score3;
};
void main()
{
struct student stu[N];
for (int i = 0; i<N;)
{
printf("请输入学号:");
scanf("%d",&stu[i].num);
printf("请输入姓名:");
gets(stu[i++].name);
}
}
//为何无法循环读入stu[i].name,运行第次走到提示输入姓名那里就跳过了,不给我输入姓名的机会..

由于在scanf()函数后要输入回车才能将数据结束,所以回车被保留在缓冲中,当遇到gets()时使gets()接受了这个回车而被跳过,要解决这个问题你要在gets()前加一条语句getchar();使getchar()接受这个回车,就不会跳过了
我以前也遇到这个问题,看了很多书才知道的,那时还不会到网上问,多花了不少时间