【发布时间】:2018-04-24 06:13:34
【问题描述】:
我目前正在学习 C,我的任务是创建一个保存在记录中的结构,我应该使用链表。我的功能之一是通过输入姓氏来删除记录。使用 fgets 后代码停止工作(没有崩溃只是停止)。
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;
}
我不认为它与链表有关,但可能是我的输入或其他东西。
EDIT1:我发现错误是我忘记在 delrec 的 while 循环中提供 temp=temp->next;。我现在当前的问题是,即使我输入了确切的姓氏,它也不会从列表中删除记录/取消链接结构。我已经编辑了代码以显示我的进度。
EDIT2:没有什么大的理由来编辑,但为了避免不想要的答案,我已经能够弄清楚如何从链接列表中删除结构。但是,如果我从头部删除结构,它会打印出非常奇怪的文本,再次编辑代码以显示进度。
【问题讨论】:
-
在每个 printf() 中添加 can \n 看看是否仍然感觉卡住了
标签: c linked-list structure fgets