Thread: structure and a linked list help with output

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    2

    structure and a linked list help with output

    this is the problem:
    Write a program that utilizes a structure and a linked list to store employee information taken from the keyboard (last name, first name, three digit employee id number). The program should traverse the linked list and display the name and id number of the employee with the lowest id number.

    My problem is that it compiles just that when I type info in it works the first time around then when i input data again first name and last name combines.

    Code:
    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>
    #define NSIZE 20
    
    typedef struct employee
    {char fname[NSIZE];
     char lname[NSIZE];
     int  id;
     struct employee*next;
    }WORK;
    
    WORK* insertit(WORK*first, char empFNAME[], char empLNAME[], int idnum);
    
    int main (void)
    {  WORK *head,
            *p;
       char namef[21],
            namel[21];
       int empID,
           j,
           k;
       char ch,
            nl;
    
    head=NULL;
    for(k=0; k<21; k++)
      { namef[k]=' ';
        namel[k]=' ';
      }
    for(j=0; j<4; j++)
       {printf("Enter the first name of the employee: \n");
        gets(namef);
        printf("Enter the last name of the employee: \n");
        gets(namel);
        printf("Enter the three digit ID number: \n");
        scanf("%d", &empID);
        head=insertit (head, namef, namel, empID);
    for(k=0; k<21; k++)
       namef[k]=' ';
       namel[k]=' ';
       }
    
    p=head;
    while (p!=NULL)
      {puts(head->fname);
       puts(head->lname);
       printf("The ID number is: ", head->id);
       p=p->next;
      }
     printf("Hit any character to continue");
     scanf("%c", &ch);
    }
    
    WORK* insertit (WORK *first, char empFNAME[], char empLNAME[], int idnum)
    {WORK *p,
          *q,
          *newp;
     int found,
         len,
         i;
         found=0;
         q=first;
         p=first;
    
    while ((p!=NULL) && (!found))
      {if (p->id<idnum)
         {q=p;
          p=p->next;
         }    
        else
          found=1;
      }
    
    newp=(WORK*) malloc(sizeof(WORK));
    newp->id=idnum;
    strncpy(newp->fname, empLNAME, 21);
    
    newp->next=p;
    if(q!=p)
      q->next=newp;
    else
      first=newp;
    return (first);
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You're using gets. That's bad.
    You're copying 21 characters into a 20 character array. That's bad.
    You may or may not get a null terminated string for your names. That's bad.

    Start there.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Tags for this Thread