首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何突破这个循环?

如何突破这个循环?
EN

Stack Overflow用户
提问于 2022-11-12 18:10:17
回答 2查看 44关注 0票数 -1

我正在编写一个程序,在这个程序中,我使用链接列表将学生添加到名册中。我成功地添加了第一个学生,但是在添加后续的学生时,我的程序打印“学生已经存在”,即使学生还不存在。下面是我的添加函数。

代码语言:javascript
复制
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,但这会导致程序中的其他问题。任何帮助都是非常感谢的。

EN

回答 2

Stack Overflow用户

发布于 2022-11-12 18:29:18

代码语言:javascript
复制
          printf("\nStudent has been added to the roster.\n");
          p = NULL;
          break; 
票数 0
EN

Stack Overflow用户

发布于 2022-11-13 05:33:01

对我起作用的是摆脱了of语句和What循环,选择了if语句。而且,我只返回了添加到列表中的学生,而不是整个列表,因此没有添加学生。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74415386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档