Hi guys,

I am trying to write a program that takes in a file, which has the last name first name and grade of a student. I then need to sort the grades from highest score to lowest with the corresponding names and then calculate the average grade. I have successfully opened the file and calculated the average but cannot figure out the sorting. This is a homework assignment so I would really just like pointers on how to do this. Thank you for the help in advance!

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

main(){

  FILE *data; 
  char line[35];
  char grade[35];
  const int a = 34;
  int i, j, l, t;
  float average, sum, g;

  data = fopen("/home/varnes/hw06/hw6_grades.txt", "r");
  if ( data == NULL ){
    printf("Error: Cannot open file\n");
    exit(1);
  }

  for ( j = 0; j < a; j++){

    while (fgets (line, sizeof(line), data) != NULL){
    printf(line);

    for ( l = 0; l < 1; l++){
      strncpy(grade, line+21, 26);
      g = atof(grade);
      sum += g;
    }

    for(i = 0; i < 33; i++){
      if((grade[i]) > (grade[i+1])){
        t = grade[i];
        grade[i] = grade[i+1];
        grade[i+1] = t;

    }
      }
    }
    printf("\n%c ", grade[i]);
  }
    average = sum/a;
    printf("\nSum is: %f", sum);
    printf("\nAverage grade: %f\n", average);


}

You need to create a structure that holds the information for one person, then create an array of those structures. As the file is read you will populate each of the structures in the array. After file reading is finished, you need to sort the array of structures. There are many algorithms for sorting, so you need to know which algorithm you are to use.

If you know how to do linked lists then sorting isn't necessary because you can add the structure to the list in sorted order.

I could see that you've tried sorting the grades in the for loop which appears to be like a bubble sort (google that) with all the swapping. Like Ancient Dragon said, there are many ways you can sort data, just search sorting algorithms and use whichever one you think you can code.

According to me you should go for Linked Lists as suggested by Ancient Dragon. Its a good solution.

According to me you should go for Linked Lists as suggested by Ancient Dragon. Its a good solution.

Wouldn't that be according to Ancient Dragon then? ;)

I think you misunderstood him -- he meant to say "in my opinion"

I think you misunderstood him -- he meant to say "in my opinion"

I understood perfectly. It was a joke, as evidenced by the smiley at the end.

You need to break up your loop into multiple loops.

1st) read the entire file in one loop
2nd) sort the data using two loops
3rd) the rest of the program

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.