- #1
evinda
Gold Member
MHB
- 3,836
- 0
Hello! (Wave)
I have a code in C where the user has to give information (id, name, surname, grade) of a student.
The id must be 5 characters, the name and the surname at most 50 characters.
The code is:
At the output I gave the following information and I get the following results:
Why at the printed ID we get ID and name together? I noticed after doing several examples that if I give ID's with less characters then it is printed normally. This occurs when I give 5 characters. Why does this occur? Where is a mistake at the program? (Thinking)
I have a code in C where the user has to give information (id, name, surname, grade) of a student.
The id must be 5 characters, the name and the surname at most 50 characters.
The code is:
Code:
#include <stdio.h>
#include <stdlib.h>
struct student
{
char id[5];
char name[50];
char surname[50];
float grade;
};
void GetInformation(struct student *ptr){
printf("Enter ID of the student: ");
scanf("%s", ptr->id);
printf("Enter the name of the student: ");
scanf("%s", ptr->name);
printf("Enter the surname of the student: ");
scanf("%s", ptr->surname);
printf("Enter the grad of the student: ");
scanf("%f", &ptr->grade);
}
int main() {
int i=0, num;
printf("Enter the number of students: ");
scanf("%d", &num);
struct student *students = malloc( num*sizeof(struct student) );
struct student *ptr=students;
for (i=0; i<num; i++){
GetInformation(ptr);
printf("\nThe ID of the student is: %s.\n", students[i].id);
printf("The name of this student is %s and the surname is %s.\n", students[i].name, students[i].surname);
printf("The grade is %f.", students[i].grade);
ptr++;
}
return 0;
}
At the output I gave the following information and I get the following results:
Code:
Enter the number of students: 1
Enter ID of the student: 12345
Enter the name of the student: Lea
Enter the surname of the student: Smith
Enter the grad of the student: 5
The ID of the student is: 12345Lea.
The name of this student is Lea and the surname is Smith.
The grade is 5.000000.
Why at the printed ID we get ID and name together? I noticed after doing several examples that if I give ID's with less characters then it is printed normally. This occurs when I give 5 characters. Why does this occur? Where is a mistake at the program? (Thinking)