I'm currently learning C, and my assignment is to create a structure that holds in records, and I am supposed to use linked-list. One of my functions is to delete a record by entering the last name. Code stops working after I use fgets(no crash just stops).
struct students
{
char firstname[21];
char lastname[21];
double score;
int zip;
struct students* next;
};
struct students* head;
void add()
{
struct students* new_node=(struct students*)malloc(sizeof(struct students));
struct students *past=head;
fflush(stdin);
new_node->next=NULL;
printf("Enter data: \n");
printf("First name: ");
fgets(new_node->firstname, 21, stdin);
printf("Last name: ");
fgets(new_node->lastname, 21, stdin);
printf("Score: ");
scanf("%lf", &new_node->score);
printf("ZIP code: ");
scanf("%d", &new_node->zip);
if(head==NULL)
{
head=new_node;
return;
}
while(past->next!=NULL)
{
past=past->next;
}
past->next=new_node;
return;
}
void delrec()
{
char last[21];
printf("Enter last name: ");
fflush(stdin);
fgets(last, 21, stdin);
struct students* temp=head;
last[strcspn(last, "\n")]=0;
if(strcmp(temp->lastname, last)==0)
{
struct students *next=temp->next;
free(temp);
temp=next;
}
while(temp!=NULL)
{
if(temp->next==NULL)
{
return;
}
if(strcmp(temp->next->lastname, last)==0)
{
struct students *next=temp->next->next;
free(temp->next);
temp->next=next;
}
temp=temp->next;
}
}
int main()
{
head=NULL;
int i, x, y;
printf("Enter 5 records:\n");
for(i=0; i<5; i++)
{
add();
}
print();
printf("What would you like to do?\n");
y=1;
while(y)
{
printf("Print records (press 1)\n");
printf("Add new record (press 2)\n");
printf("Delete record (press 3)\n");
printf("Exit the program (press 0)\n");
scanf("%d", &x);
switch(x)
{
case 0:
y=0;
break;
case 1:
print();
break;
case 2:
add();
break;
case 3:
delrec();
break;
}
}
return 0;
}
I don't think it has to do with linked-list though, but maybe my inputs or something.
EDIT1: I have found that the error is I forgot to provide temp=temp->next;
on the while loop for delrec. My current problem now is that even though I type the exact last name, it will not delete the record/unlink the structure from the list. I have edited the code to show my progress.
EDIT2: No big reason to edit, but just so I don't get unwanted answers, I have been able to figure out how to delete the structure from the linked-list. However, if I delete the structure from the head, it will print very weird text, edited code again to show progress.