Reputation: 548
I've got a task that I need to input all the information of students (ID, name, grade) as the database as the source code below. My source code here is totally valid about the syntax (no error informed as my gcc does) but I can't input the grades of students. When I run my program, it skipped over the step of input the grade of student and step to input the next student ID. I've put getchar()
to hold the \n
character but it maybe not work at all or there is another reason for this error.
typedef struct
{
char id[10];
char name[50];
float grade;
char assess;
}student;
student std[50];
do {
printf("How many students you want to add?\n");
scanf("%d", &num);
if(num<0 || num>50)
printf("Your number must be positive or smaller than or equal to 50!\n");
} while(num<0||num>50);
for(i = a; i < num; i++)
{
printf("Student's id No.%d:", i);
fgets(std[i].id, MAX, stdin);
getchar();
printf("Student's name No.%d:", i);
fgets(std[i].name, MAX, stdin);
getchar();
printf("Student's grade No.%d:", i);
do {
scanf("%f", std[i].grade);
if(std[i].grade < 0 || std[i].grade > 10)
printf("Please re-input grade, it must be between 0 and 10\n");
} while(std[i].grade < 0 || std[i].grade > 10);
std[i].assess=assess(std[i].grade);
}
Upvotes: 0
Views: 42
Reputation: 1221
To write data to memory location allocated for variables, you need to specify the address of the variable, you're using scanf
on. So scanf("%f", std[i].grade);
should be modified to scanf("%f", &(std[i].grade) );
.
Due to aforementioned reason, your code has undefined behavior, which often but not always, results in Segmentation fault.
Upvotes: 1