Home > Mobile >  How to break out of this for loop?
How to break out of this for loop?

Time:11-13

I am writing a program in which I add students to a roster using linked lists. I am successful at adding the first student, but upon adding subsequent students, my program prints "Student already exists" even when the student doesn't exist yet. Below is my add function.

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;
}

If anyone can help me understand how to fix this so that the for loop doesn't keep executing after the student is added to the list, I'd appreciate it.

It doesn't seem as though my break statement is working. I've tried making the return to new_student occur within my else statement, but that causes other issues in my program. Any help is appreciated.

CodePudding user response:

          printf("\nStudent has been added to the roster.\n");
          p = NULL;
          break; 

CodePudding user response:

What worked for me was getting rid of my else statement and while loop and opting for an if statement. Also, I was only returning the student added to the list, rather than the entire list, so students were not being added.

  • Related