Я прочитал данные из txt файла и сохранил их в массиве struct, и хочу отсортировать данные по полю имени - PullRequest
0 голосов
/ 29 сентября 2019

Этот код не выдает никаких ошибок, но отображает массив со старыми значениями без сортировки по полю имени, он работает вплоть до чтения txt-файла, хранящего данные в массиве struct Student, который является экземпляром struct person, а затем при использовании кода дляотсортировать и распечатать результаты отсортированного массива.но это не работает

#include < stdio.h > 
#include < string.h >

int main() {
    // read data from txt file and stores
    // in a struct array

    storeInarraySort();

}

int storeInarraySort() {

     // struct person with 4 fields
     struct person {
         char name[100];
         char address[100];
         char IDnumber[20];
         int age;
     };


     FILE * file = fopen("personout.txt", "r");

     // declares an struct array to store data
     struct person student[10];

     int k = 0;

     if (file != NULL)
     {
         char line[128]; /* or other suitable maximum line size */
         /* read a line */
         while (fgets(line, sizeof line, file) != NULL)
         {

             // stores values in struct array
             sscanf(line, " %99[^,], %99[^,], %19[^,], %d", student[k].name,
                 student[k].address, student[k].IDnumber, & student[k].age);
             k++;

         }
         printf("%d\n", k); // no of records in array

         fclose(file);


         // number of records k  r=k first for loop
         // inner for loop s=r+1
         //char temp;
         //struct person temp;

         for (int r = 0; r < k - 1; r++) {
             for (int s = r + 1; r < k; r++) {

                 if (strcmp(student[r].name, student[s].name) > 0) {

                     struct person temp = student[r];
                     //strcpy(temp,student[r]);
                     student[r] = student[s];
                     //strcpy(student[r],student[s]);
                     student[s] = temp;
                     //strcpy(student[s],temp);
                 }


             }


         }

         // prints struct array to check
         for (int t = 0; t < k; t++) {
             printf("%s\n %s\n %s\n %d\n ", student[t].name,
                 student[t].address, student[t].IDnumber, student[t].age);
         }

     }


}

1 Ответ

0 голосов
/ 29 сентября 2019

Использовать сортировку выбора для сортировки.

void swap(int *xp, int *yp)  
{  
    int temp = *xp;  
    *xp = *yp;  
    *yp = temp;  
} 

void selectionSort(int arr[], int n)  
{  
    int i, j, min_idx;  

    // One by one move boundary of unsorted subarray  
    for (i = 0; i < n-1; i++)  
    {  
        // Find the minimum element in unsorted array  
        min_idx = i;  
        for (j = i+1; j < n; j++)  
        if (strcmp(arr[j].name , arr[min_idx].name) < 0)  
            min_idx = j;  

        // Swap the found minimum element with the first element  
        swap(&arr[min_idx], &arr[i]);  
    }  
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...