pvjc24/cv5/program.c

83 lines
2.2 KiB
C
Raw Normal View History

2024-03-21 22:55:24 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-21 23:04:31 +00:00
#define SIZE 100
2024-03-21 22:55:24 +00:00
2024-03-21 23:04:31 +00:00
struct student {
char name[SIZE];
int votes;
};
// Funkcia pre porovnanie dvoch študentov pri triedení
int compare(const void* p1, const void* p2) {
const struct student* s1 = (const struct student*)p1;
const struct student* s2 = (const struct student*)p2;
2024-03-21 22:55:24 +00:00
2024-03-21 23:04:31 +00:00
// Porovnanie podľa počtu hlasov
return s2->votes - s1->votes;
}
// Funkcia na vyhľadanie študenta v databáze
int find_student(struct student* students, int size, const char* name) {
for (int i = 0; i < size; i++) {
if (strcmp(students[i].name, name) == 0) {
return i; // Nájdený študent
}
2024-03-21 22:55:24 +00:00
}
2024-03-21 23:04:31 +00:00
return -1; // Študent nenájdený
2024-03-21 22:55:24 +00:00
}
int main() {
2024-03-21 23:04:31 +00:00
struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student));
int size = 0;
char line[SIZE];
char name[SIZE];
int votes;
while (1) {
2024-03-21 23:07:54 +00:00
printf("Enter votes and student name (or 'q' to quit): ");
2024-03-21 23:04:31 +00:00
fgets(line, SIZE, stdin);
// Kontrola ukončenia vstupu
if (strcmp(line, "q\n") == 0 || strcmp(line, "Q\n") == 0) {
break;
2024-03-21 22:55:24 +00:00
}
2024-03-21 23:07:54 +00:00
// Načítanie počtu hlasov a mena zo vstupu
if (sscanf(line, "%d %s", &votes, name) != 2) {
2024-03-21 23:04:31 +00:00
printf("Invalid input. Please try again.\n");
continue;
2024-03-21 22:55:24 +00:00
}
2024-03-21 23:04:31 +00:00
// Vyhľadanie študenta v databáze
int index = find_student(database, size, name);
if (index == -1) {
// Študent nenájdený, pridáme ho do databázy
if (size < SIZE) {
strcpy(database[size].name, name);
database[size].votes = votes;
size++;
} else {
printf("Database is full.\n");
}
} else {
// Študent nájdený, zvýšime počet hlasov
database[index].votes += votes;
2024-03-21 22:55:24 +00:00
}
}
2024-03-21 23:04:31 +00:00
// Triedenie databázy podľa počtu hlasov
qsort(database, size, sizeof(struct student), compare);
// Výpis triedenej databázy
printf("\nSorted database:\n");
for (int i = 0; i < size; i++) {
2024-03-21 23:07:54 +00:00
printf("%s: %d votes\n", database[i].name, database[i].votes);
2024-03-21 22:55:24 +00:00
}
2024-03-21 23:04:31 +00:00
2024-03-21 22:55:24 +00:00
return 0;
}