pvjc20/du5/program.c

150 lines
3.5 KiB
C
Raw Permalink Normal View History

2020-04-10 08:24:17 +00:00
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#include<inttypes.h>
#include<errno.h>
#include<ctype.h>
struct Student {
long pocet_hlasov;
char meno[256];
};
int compare_students(const void *a, const void *b);
void sort_students(struct Student *students[], int n);
void swap(struct Student **s1, struct Student **s2);
int main() {
char buffer[512];
char *retValPtr;
struct Student *studenti[1000];
int count = 0;
while ((retValPtr = fgets(buffer, sizeof(buffer), stdin)) != 0 && feof(stdin) == 0 && ferror(stdin) == 0) {
long pocet_hlasov;
char meno[256];
char *next;
pocet_hlasov = strtoimax(buffer, &next, 10);
if (errno == ERANGE || next == 0 || next == &buffer[0]) {
break;
}
// mame medzeru medzi menom a poctom hlasov?
if (*next != ' ' || *next == '\n' || *next == '\0') {
break;
}
next++;
// meno zacina neplatnym znakom alebo nie je zadane
if (isspace(*next) || *next == '\n' || *next == '\0') {
break;
}
char *ptr_meno = meno;
while (ptr_meno < (meno + sizeof(meno) - 2)
&& *next != '\n'
&& *next != '\0') {
*ptr_meno = *next;
next++;
ptr_meno++;
}
*ptr_meno = '\0';
struct Student *student = 0;
// najdeme uz zadaneho studenta s rovnakym menom ak existuje
for (int i = 0; i < count; i++) {
struct Student *s = studenti[i];
if (strcmp(s->meno, meno) == 0) {
student = s;
break;
}
}
if (student == 0) {
student = (struct Student*) malloc(sizeof(struct Student)); // alokujeme miesto pre noveho studenta
strcpy(student->meno, meno);
student->pocet_hlasov = pocet_hlasov;
studenti[count] = student;
count++;
} else {
student->pocet_hlasov += pocet_hlasov;
}
}
if (count == 0) {
2020-04-10 08:26:32 +00:00
puts("Nepodarilo nacitat nic");
2020-04-10 08:24:17 +00:00
return 0;
}
// zoradime studentov
// qsort(studenti, count, sizeof(struct Student*), compare_students);
sort_students(studenti, count);
// vypiseme vysledky
puts("Vysledky:");
for (int i = 0; i < count; i++) {
struct Student *student = studenti[i];
printf("%ld %s\n", student->pocet_hlasov, student->meno);
}
// nakoniec treba vycistit neporiadok ktory sme spravili
for (int i = 0; i < count; i++) {
free(studenti[i]);
}
return 0;
}
int compare_students(const void *a, const void *b) {
const struct Student *s1 = (struct Student*)a;
const struct Student *s2 = (struct Student*)b;
if (s1 == 0 || s2 == 0) {
return 0;
}
if (s1->pocet_hlasov != s2->pocet_hlasov) {
if (s1->pocet_hlasov < s2->pocet_hlasov) {
return 1;
} else {
return -1;
}
}
return strcmp(s1->meno, s2->meno);
}
void sort_students(struct Student *students[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
int result = compare_students(students[j], students[j + 1]);
if (result == 0) {
continue;
} else if (result > 0) {
swap(&students[j], &students[j + 1]);
}
}
}
}
void swap(struct Student **s1, struct Student **s2) {
struct Student *temp = *s1;
*s1 = *s2;
*s2 = temp;
}