Advertisement
visoft

citire_studenti_si_sortare

Dec 6th, 2019
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. /*
  2.  ============================================================================
  3.  Name        : sortat_structura.c
  4.  Author      :
  5.  Version     :
  6.  Copyright   : Your copyright notice
  7.  Description : Hello World in C, Ansi-style
  8.  ============================================================================
  9.  */
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14.  
  15. typedef struct{
  16.     char nume[20];
  17.     char prenume[20];
  18.     int nr_matricol;
  19.     int an;
  20.     int partial;
  21. }Student;
  22.  
  23. void sortare_bubble(Student*studenti, int nr_total){
  24.     for(int i=0;i<nr_total;i++){
  25.         for(int j=0;j<nr_total-1;j++){
  26.             Student s1, s2;
  27.             s1 = studenti[j];
  28.             s2 = studenti[j+1];
  29.             if (strcmp(s1.nume, s2.nume) > 0){
  30.                 studenti[j] = s2;
  31.                 studenti[j+1] = s1;
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37.  
  38. int main(void) {
  39.     char *nume_fisier = "src/in.txt";
  40.     FILE *f;
  41.     f = fopen(nume_fisier, "r");
  42.     if (f == NULL){
  43.         printf("Nu pot deschide %s", nume_fisier);
  44.         return -1;
  45.     }
  46.     int nr_linii;
  47.     char * linie_tmp = (char*)malloc(100*sizeof(char));
  48.     fscanf(f, "%d\n", &nr_linii);
  49.     int i = 0;
  50.     Student *studenti = (Student*)malloc(nr_linii*sizeof(Student));
  51.     while(i<nr_linii){
  52.         fgets(linie_tmp, 99, f);
  53.         int l;
  54.         l = strlen(linie_tmp);
  55.         if (l <= 2)
  56.             continue;
  57.         sscanf(linie_tmp, "%s %s %d %d %d",studenti[i].nume, studenti[i].prenume,
  58.                 &studenti[i].nr_matricol, &studenti[i].an, &studenti[i].partial);
  59.         i++;
  60.     }
  61.  
  62.     sortare_bubble(studenti, nr_linii);
  63.  
  64.     for(i=0; i<nr_linii; i++){
  65.         printf("%s %s %d\n",studenti[i].nume,studenti[i].prenume, studenti[i].partial);
  66.     }
  67.  
  68.     printf("nr linii: %d", nr_linii);
  69.     free(studenti);
  70.     free(linie_tmp);
  71.     fclose(f);
  72.     return EXIT_SUCCESS;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement