Hi,
I've used qsort to extract the unique student IDs by jumping every four because there's 80 rows of data and twenty students.
I want to make sure it's all working and there's something very strange going on. If you look at my code, when it comes to initialising the structure with the unique student IDs it will happily print them after each one has been initialised inside the for loop (which suggests to me it's obviously done it) but, however, when I want to print them again outside the for loop in another for loop as a "double-check" it goes horribly wrong, presumably they're not in there at all? If you traverse the code to the bottom you'll see my comments.
Now in my for loop, j is going to be incremented 20 times which will correspond to the #define STUDENTS 20. So imagine the array of structure db[j] , the first loop will set i and j both to zero, retrieve the first unique ID and store it in the structure. Then i is incremented by four to acces the next unique ID and then j is incremented by 1 to insert this new ID in the structure.
Hope that makes sense.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ROWS 80
#define SIZE 100
#define STUDENTS 20
int string_compare(void const *x, void const *y)
{
return strcmp(*(char**)x, *(char**)y);
}
struct student
{
char student_ID[SIZE];
};
int main(void)
{
FILE* input;
int i,j,data_items;
int records=0;
char buffer_IDs[ROWS][SIZE];
char buffer_subjects[ROWS][SIZE];
int marks[ROWS];
char *string_ptrs[ROWS];
struct student db[STUDENTS];
if((input=fopen("C:\\marks\\marks.txt", "r"))==NULL)
perror("File open failed!");
else
{
while ( ( data_items=fscanf(input, "%s %s %d", buffer_IDs[records], buffer_subjects[records], &marks[records])) == 3)
{
printf("%s %s %d\n", buffer_IDs[records], buffer_subjects[records], marks[records]);
string_ptrs[records]=buffer_IDs[records];
records++;
if ( records > ROWS)
{
break;
}
}
}
qsort(string_ptrs, records, sizeof(char*), string_compare);
for(i=0;i<records;i=i+4)
{
j=0;
strcpy(db[j].student_ID,string_ptrs[i]);
printf("%s\n",db[j].student_ID); /*Happily prints the unique IDs contained in the structure*/
j++;
}
for
(i=0;i<STUDENTS;i++)
printf(
"%s\n",db[i].student_ID); /*Does NOT print them outside the for loop which initialises the structure. */
fclose(input);
return 0;
}