我正在编写一个程序,在这个程序中,我使用链接列表将学生添加到名册中。我成功地添加了第一个学生,但是在添加后续的学生时,我的程序打印“学生已经存在”,即使学生还不存在。下面是我的添加函数。
struct student *add(struct student *list){
struct student *p;
struct student *new_student = malloc(sizeof(struct student));
printf("Enter the student's last name: ");
read_line(new_student->last, NAME_LEN);
printf("Enter the student's first name: ");
read_line(new_student->first, NAME_LEN);
printf("Enter the student's email: ");
read_line(new_student->email, EMAIL_LEN);
printf("Enter the student's instrument: ");
read_line(new_student->instrument, INSTRUMENT_LEN);
printf("Enter the student's group name: ");
read_line(new_student->group, GROUP_LEN);
if(new_student == NULL){
printf("\nMalloc failed.\n");
return list;
}
if(list==NULL){
return new_student;
}
for(p=list;p!=NULL; p=p->next){
if((strcmp(p->first,new_student->first)==0) &&
(strcmp(p->last, new_student->last)==0)){
printf("\nThis student already exists.\n");
return list;
}
else{
while(p->next==NULL){
p->next = new_student;
new_student->next = NULL;
printf("\nStudent has been added to the roster.\n");
break; //FOR LOOP NOT BREAKING?
}
}
}
return new_student;
}如果有人能帮助我理解如何解决这个问题,以便在学生被添加到列表后for循环不再继续执行,我将非常感激。
我的休息声明似乎不起作用。我尝试在else语句中返回new_student,但这会导致程序中的其他问题。任何帮助都是非常感谢的。
发布于 2022-11-12 18:29:18
printf("\nStudent has been added to the roster.\n");
p = NULL;
break; 发布于 2022-11-13 05:33:01
对我起作用的是摆脱了of语句和What循环,选择了if语句。而且,我只返回了添加到列表中的学生,而不是整个列表,因此没有添加学生。
https://stackoverflow.com/questions/74415386
复制相似问题