I read a text file and stored the data in a struct array, then tried to sort it and to print the un-sorted and sorted arrays. It works up to reading the array text and storing in the array, but the sorting function does not run without giving any errors. what is wrong with it? I used the strcmp() function to compare student[s]:
#include <stdio.h>
struct person { //struct person with 4 fields
char name[100];
char address[100];
char IDnumber[20];
int age;
};
int main (void) {
FILE *file = fopen ( "personout.txt", "r");
struct person student[10]; // declares an struct array to store data
int k = 0;
if (file != NULL) {
char line[300];
while ( k < 10 && fgets ( line, sizeof line, file ) != NULL ) {
if ( 4 == sscanf ( line, " %99[^,], %99[^,], %19[^,], %d",
student[k].name, student[k].address, student[k].IDnumber, &student[k].age))
{
printf ( "%s\n Un-sorted array");
printf ( "%s\n", student[k].name);
printf ( "%s\n", student[k].address);
printf ( "%s\n", student[k].IDnumber);
printf ( "%d\n", student[k].age);
k++;
}
}
fclose ( file );
}
sortarray();
// prints sorted array
printf ( "%s\n Sorted array");
for (int t=0;t<10;t++) {
printf ( "%s\n", student[t].name);
printf ( "%s\n", student[t].address);
printf ( "%s\n", student[t].IDnumber);
printf ( "%d\n", student[t].age);
t++;
}
}
void sortarray(){
// number of records a r=a first for loop
// inner for loop s=r+1
struct person temp,student[10];
int a=10;
for (int r=0;r<a-1;r++) {
for (int s=r+1;r<a;s++) {
if (strcmp(student[r].name, student[s].name) > 0) {
temp = student[r];
student[r] =student[s];
student[s] = temp;
}
}
}
}
printf ( "%s\n Un-sorted array")andprintf ( "%s\n Sorted array")??? Take some time to explain those calls to your rubber duck.