I am trying to make a program that manages info of students. But I just can't use pointer well due to lack of my c programming skill.
Here is source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int id;
char fName[8];
char lName[8];
} Student;
void main()
{
int size = 0;
int i = 0;
/* get max lines */
scanf("%d", &size);
Student *students = (Student*) malloc(sizeof(Student) * size); // allocate whole table
Student *pointAt = students; // pointer used to point whole table by memory address
/* retrieves data from stdin */
for (i = 0; i < size; i++)
{
scanf("%d", &((*pointAt).id));
printf("recorded id at %d is %d\n", i, (*pointAt).id);
fgets((*pointAt).fName, sizeof((*pointAt).fName), stdin);
printf("recorded fName at %d is %s\n", i, (*pointAt).fName);
fgets((*pointAt).lName, sizeof((*pointAt).lName), stdin);
printf("recorded lName at %d is %s\n", i, (*pointAt).lName);
while (getchar() != '\n')
;
}
free(students);
}
And the text file I read from, called test.txt, is:
2
11223344 Jennifer Smith
22334455 John Bob
*Note that here 2 on the first line is used to set the size of dynamically allocated struct, used at : Student students = (Student)malloc(sizeof(Student) * size); because there are only 2 students, Jennifer and John.
And here is command I run to test this:
a.out < test.txt
And here is output:
recorded id at 0 is 11223344
recorded fName at 0 is Jennif
recorded lName at 0 is er Smit
recorded id at 1 is 22334455
recorded fName at 1 is John B
recorded lName at 1 is ob
^Z
Suspended
The problems are:
It seems it retrieves studentID well, but not first name(fName) and last name(lName). It seems fName retrieves space as well, which it should avoid of.
Program gets into infinite loop due to use of "while (getchar() != '\n');" to clear input buffer. So I pressed ctrl+z(^Z) to force terminate program, which you can see in my sample output.
How can I fix this? Thank you very much..
Changed part of source after first fixing:
for(i=0; i<size; i++) {
scanf("%d", &((*pointAt).id));
printf("recorded id at %d is %d\n", i, (*pointAt).id);
getchar();
fgets((*pointAt).fName, sizeof((*pointAt).fName), stdin);
printf("recorded fName at %d is %s\n", i, (*pointAt).fName);
getchar();
fgets((*pointAt).lName, sizeof((*pointAt).lName), stdin);
printf("recorded lName at %d is %s\n", i, (*pointAt).lName);
}
And output after first fixing:
recorded id at 0 is 11223344
recorded fName at 0 is Jennifer
recorded lName at 0 is Smith
recorded id at 1 is 22334455
recorded fName at 1 is John Bob
recorded lName at 1 is Smith
iin yourforloop. But you don't do anything useful with it to progress in your students list.