Question

I have a code which saves student numbers (stdnum) that located in a doubly linked list inside another doubly linked list into a file. I noticed that sometimes, it prints "(null)" and extra blank spaces. How do I avoid these? Here's my code:

typedef struct frn{ //structure for friend
char stdnum[20];
struct frn *next;
struct frn *prev;
}friend;

typedef struct std{ //structure for student
char stdnum[20];
char name[20];
char course[10];
struct frn *friendh; 
struct frn *friendt;
struct std *next;
struct std *prev;
}student;



FILE *fp1;
student *y = h->next;
friend *y1;
fp1 = fopen("friends.txt", "w");
    if(y != t){
        while(y != t){
            y1 = y->friendh;
            while(y1 != NULL){ 
                fprintf(fp1, "%s\n", y1->prev->stdnum);
                y1 = y1->next;
            }
            y = y->next;
        }
    }
fclose(fp1);
Était-ce utile?

La solution

After reading your comments, here is why its printing NULL:

fprintf(fp1, "%s\n", y1->prev->stdnum)

what happens when you are on the very first node of your linked list (y1)( first time you enter that inner while )? When you do y1->prev->stdnum you are accessing random memory Or if you have initialised your linked list to NULL values for empty values. That is what gets printed.

Then straight after printing that null you do y1 = y1->next. which takes you to the 2nd node of your linked list.

Now once again when you do :

fprintf(fp1, "%s\n", y1->prev->stdnum)

now you are printing the 'stdnum' value of the first node, which you mentioned in the comments is empty. So fprintf prints out a empty space.

Can you verify that the null and blank space occur right next to each other?

You can fix it like this:

typedef struct frn{ //structure for friend
    char stdnum[20];
    struct frn *next = NULL;
    struct frn *prev = NULL;
}friend;

fp1 = fopen("friends.txt", "w"); // I would highly recommend, you put an error check here to verify if the file opened or not 
if(y != t){
    while(y != t){
        y1 = y->friendh;
        while(y1 != NULL){ 
            if(y1->prev==NULL){
               y1 = y1->next;
            }else{
            fprintf(fp1, "%s\n", y1->prev->stdnum);
            y1 = y1->next;
            }
        }
        y = y->next;
    }
}
fclose(fp1);

Autres conseils

A couple of things to note:

  • You shouldn't use the name "friend", since it's a keyword in C++

  • Check if you could open the file

  • The first if (if(y != t)) is unnecessary (already coverred by the while-loop

  • What is "t"? Is it a special student number?

  • You are printing a string (%s), not a number (%d). Are you saving the student numbers as strings?

  • Please show us the structure of the students. It's hard to answer your question without knowing how you build your list

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top