102 lines
2.2 KiB
C
102 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define SIZE 100
|
|
|
|
|
|
struct student {
|
|
char name[SIZE];
|
|
int votes;
|
|
};
|
|
/*char* read_line(char* buffer, int size) {
|
|
char* result = fgets(buffer, size, stdin);
|
|
if (result) {
|
|
// Удаление символа новой строки, если он есть
|
|
char* newline = strchr(buffer, '\n');
|
|
if (newline)
|
|
*newline = '\0';
|
|
}
|
|
return result;
|
|
}*/
|
|
|
|
|
|
char* read_line(char* buffer, int size) {
|
|
char* result = fgets(buffer, size, stdin);
|
|
if (result) {
|
|
|
|
buffer[strcspn(buffer, "\n")] = '\0';
|
|
}
|
|
return result;
|
|
}
|
|
|
|
|
|
int parse_int(const char* str) {
|
|
return atoi(str);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
|
|
void add_student(struct student* students, int* size, const char* name, int votes) {
|
|
|
|
int index = find_student(students, *size, name);
|
|
if (index == -1) {
|
|
if (*size < SIZE) {
|
|
strcpy(students[*size].name, name);
|
|
students[*size].votes = votes;
|
|
(*size)++;
|
|
} else {
|
|
printf("Database is crowded!\n");
|
|
}
|
|
} else {
|
|
students[index].votes += votes;
|
|
}
|
|
}
|
|
|
|
|
|
int compare_students(const void* p1, const void* p2) {
|
|
const struct student* s1 = (const struct student*)p1;
|
|
const struct student* s2 = (const struct student*)p2;
|
|
|
|
|
|
if (s1->votes != s2->votes) {
|
|
return s2->votes - s1->votes;
|
|
} else {
|
|
|
|
return strcmp(s1->name, s2->name);
|
|
}
|
|
}
|
|
|
|
/*int main() {
|
|
struct student database[SIZE];
|
|
int size = 0;
|
|
|
|
char line[SIZE];
|
|
|
|
|
|
while (read_line(line, SIZE)) {
|
|
int votes = parse_int(line);
|
|
read_line(line, SIZE);
|
|
add_student(database, &size, line, votes);
|
|
}
|
|
|
|
|
|
qsort(database, size, sizeof(struct student), compare_students);
|
|
|
|
|
|
printf("Vysledky hlasovania:\n");
|
|
for (int i = 0; i < size; ++i) {
|
|
printf("%s: %d Hlas(ov) \n", database[i].name, database[i].votes);
|
|
}
|
|
|
|
return 0;
|
|
}*/
|