为什么此代码不接受字符输入?

时间:2019-09-19 14:41:41

标签: c char structure

我创建了一个结构Student,用于存储学生的姓名,年龄和性别。 在接受性别输入时,我的程序不接受char数据类型的输入(性别-'M'或'F')。

#include<stdio.h>

struct Student
{
    char name [25];
    int age;
    char gender;
};

struct Student stud[5];
int i;

void ask()
{
    for (i = 0; i<=5; i++)
    {
        printf("\nEnter details of student %d:",i+1);
        printf("\nEnter name: ");
        scanf("%s", stud[i].name);
        printf("\nEnter age: ");
        scanf("%d",&stud[i].age);
        printf("\nEnter gender: ");
        scanf("%c",&stud[i].gender);
    }
    printf("\nDisplaying student record:\n");
    for(i = 0; i<=5; i++)
    {
        printf("\nStudent name is: ",stud[i].name);
        printf("\nAge is: ",stud[i].age);
        printf("\nGender: ",stud[i].gender);
    }
}

void main()
{
    ask();
}

我希望输出为:

Enter the details of student1:
Enter Name: xyz
Enter age: 20
Enter gender: F
Enter the details of student2:

但实际输出是:

Enter the details of student1:
Enter Name: xyz
Enter age: 20
Enter gender:
Enter the details of students2:
Enter name:

0 个答案:

没有答案