Abhirup Bakshi
Abhirup Bakshi

Reputation: 41

Reading a file containing student names and ages and displaying them in sorted order

When I run this program, it only prints names upto 'I' and not all the way to 'Z'. I've tried to first read the file and store it's contents into a linked list and then display the contents in sorted order. Below there is the file from which the program is reading and the program itself. Please help.

The File:

Samir 20

Arup 18

Neha 22

Ashim 19

Issac 21

The Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;

    struct student
    {
        char name[20];
        int age;
        struct student *pre, *next;
    };
    struct student *s, *f;
    s = (struct student *)malloc(sizeof(struct student));
    s->pre = NULL;
    s->next = NULL;
    f = s;

    fp = fopen("A.txt", "r");
    if(fp == NULL)
    {
        printf("Not Opened");
        exit(0);
    }

    while(1)
    {
        if(fscanf(fp, "%s %d", s->name, &s->age) == EOF)
        {
            s = s->pre;
            s->next = NULL;
            break;
        }
        else
        {
           s->next = (struct student *)malloc(sizeof(struct student));
           s->next->pre = s;
           s->next->next = NULL;
           s = s->next;
        }
    }

    s = f;

    char ch = 'A';

    while(1)
    {
        if(ch == 'Z'+1)
            break;

        while(1)
        {
            if(f->name[0] == ch)
            {
                printf("%s %d\n", f->name, f->age);
                f->next->pre = f->pre;
                f->pre->next = f->next;
                if(f->next == NULL)
                    break;
                else
                    f = f->next;
            }

            if(f->next == NULL)
                break;
            else
                f = f->next;
        }

        ch = ch +1;
        f = s;
    }

    fclose(fp);
}

Upvotes: 0

Views: 238

Answers (2)

Alex
Alex

Reputation: 357

The issue is with the following lines:

f->next->pre = f->pre;
f->pre->next = f->next;

If you remove these then the list is printed just fine. However, only the printing is ordered not the list. If you'd like to order the list then see:

Sort a Linked list using C

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

Seems you mix two concepts: sorting and printing.

if(f->name[0] == ch) then you print it and you re-link the list. I don't know why you re-link it and I didn't check if you did it right to sort it (I feel it is not).

Either first sort the list (e.g. implement a bubble or use quick sort) and then print it, or just print the list as you do now but remove the re-linking (then it would print fine - except that AB could be printed before AA because you only check the first letter).

Upvotes: 0

Related Questions