I'm writing the program with the topic like this: Enter data for students with ID, name, and GPA by using dynamic allocation for these students. Find out the student with the highest GPA, then print out all information.
The program I write has the problems like this:
- If I use scanf("%s", ) for getting input for name and ID, the program just run correctly if I input name with one phrase (like Jack), it will be wrong if I input name with two phrases (like Jack Grealish), the phrase "Grealish" will be put into the place of ID.
- I try to fix it by replacing scanf("%s", ) by gets(), but when I run the program, it skips the input part of name. However, when I try to input a name with two phrases into the input part of ID, the program run correctly.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct Student
{
char name[50];
char ID[10];
double GPA;
}student;
main()
{
int n, i;
student *arrStu;
printf("Enter number of students: ");
scanf("%d", &n);
arrStu = (student*) malloc(n * sizeof(student));
if (arrStu == NULL)
{
printf("Error in allocating the data array.\n");
exit(1);
}
for (i = 0; i < n; i++)
{
printf("\nEnter student name: ");
scanf("%s", arrStu[i].name);
//gets(arrStu[i].name);
printf("Enter student ID: ");
scanf("%s", arrStu[i].ID);
//gets(arrStu[i].ID);
printf("Enter student GPA: ");
scanf("%lf", &arrStu[i].GPA);
}
double max = arrStu[0].GPA;
for (i = 0; i < n; i++)
{
if (arrStu[i].GPA > max)
max = arrStu[i].GPA;
}
for (i = 0; i < n; i++)
{
if (arrStu[i].GPA == max)
{
printf("\nStudent has highest GPA is: %s", arrStu[i].name);
printf("\nStudent ID is: %s", arrStu[i].ID);
printf("\nStudent GPA is %0.2lf", arrStu[i].GPA);
}
}
free(arrStu);
}
Hope that anyone can help me find the problem in my code. Thank you very much.