Advertisement
Guest User

Untitled

a guest
Mar 26th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include<string.h>
  3. #include <stdlib.h>
  4. #define SIZE 100
  5. //Struktura
  6. struct student{  
  7.     char name[SIZE];  
  8.     int votes;  
  9. };
  10.  
  11. int find_student(struct student* students,int size, const char* name){
  12.     int i = size;
  13.     while (i >= 0){
  14.         if(strcmp(students[i].name, name)==0){
  15.             return i;
  16.         }
  17.         i--;
  18.     }
  19.     return -1;
  20. }
  21.  
  22. int compareV(const void* p1, const void* p2){
  23.     struct student* s1 = (struct student*)p1;
  24.     struct student* s2 = (struct student*)p2;
  25.     if (s2->votes == s1->votes){
  26.            return strcmp(s1->name,s2->name);
  27.     }
  28.     else{
  29.     return (s2->votes - s1->votes);
  30.  
  31.     }
  32.     }
  33.  
  34.  
  35. int main(){
  36.    
  37.     //Zadefinovanie struktury
  38.     struct student databaza[SIZE];
  39.     memset(databaza,0,SIZE*sizeof(struct student));
  40.     int size = 0;
  41.     int i=0;
  42.    
  43.     //nacitavanie
  44.     while(1){
  45.     //Deklaracia
  46.     char line[SIZE];
  47.     memset(line,0,SIZE);
  48.    
  49.     //Samotne nacitavanie
  50.     char* r = fgets(line,SIZE,stdin);
  51.     if (r == NULL){
  52.     break;
  53.     }
  54.    
  55.     //Nacitanie poctu hlasov
  56.     char* end = NULL;
  57.     int value = strtol(line,&end,10);
  58.     if (value == 0){
  59.         break;
  60.     }
  61.  
  62.     //Zapisanie poctu hlasov
  63.     databaza[size].votes = value;
  64.    
  65.     //Nacitanie mena
  66.     char name[SIZE];
  67.     memset(name,0,SIZE);
  68.     char* zaciatok_mena = end + 1;
  69.     int velkost_mena = strlen(zaciatok_mena) - 1;
  70.     if (velkost_mena > 0){
  71.         memcpy(name,zaciatok_mena,velkost_mena);
  72.     }
  73.     else {
  74.        break;
  75.     }
  76.    
  77.     //Zapisovanie mena do Struct
  78.     int id = find_student(databaza,size,name);
  79.    
  80.     if (id< 0){
  81.     // Skopirujte zaznam na posledne miesto v poli
  82.     memcpy(databaza[size].name,name,velkost_mena);
  83.     // Zvacsite pocet zaznamov
  84.     size+=1;
  85.     }
  86.     else {
  87.     databaza[id].votes = value + databaza[id].votes;
  88.     }
  89.     }
  90.    
  91.     int n = sizeof(databaza) / sizeof(struct student);
  92.    
  93.     qsort(databaza, n, sizeof(struct student), compareV);
  94.  
  95.    
  96.     //Vypisovanie
  97.     puts("Vysledky:");
  98.     for (i=0; i<size;i++){
  99.     printf("%d %s\n", databaza[i].votes, databaza[i].name);
  100.     }
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement