This commit is contained in:
Tančáková 2024-03-20 15:57:31 +01:00
parent d2f32470b6
commit 587d2f4e11

View File

@ -5,68 +5,49 @@
#define MAX_NAME_LENGTH 100 #define MAX_NAME_LENGTH 100
#define MAX_BUFFER_LENGTH 256 #define MAX_BUFFER_LENGTH 256
// Structure to store student information #define SIZE 100
typedef struct {
char name[MAX_NAME_LENGTH]; struct student {
char name[SIZE];
int votes; int votes;
} Student; };
struct student database[SIZE];
// Comparison function for sorting students by votes and name memset(database, 0, SIZE * sizeof(struct student));
int compare_students(const void *a, const void *b) { int size = 0;
const Student *student_a = (const Student *)a; char line[SIZE];
const Student *student_b = (const Student *)b; memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
// First compare by number of votes if (r == NULL) {
if (student_a->votes != student_b->votes) { // Nastal koniec vstupu
return student_b->votes - student_a->votes; // Sort in descending order }
char *end = NULL;
int value = strtol(line, &end, 10);
if (value == 0) {
// Prevod sa nepodaril
} }
// If votes are tied, compare lexicographically by name // Pre pokračovanie získame meno študenta
return strcmp(student_a->name, student_b->name); char name[SIZE];
memset(name, 0, SIZE);
char *name_start = end + 1;
int name_length = strlen(name_start) - 1; // Nezahrňujeme koniec riadka
if (name_length > 0) {
memcpy(name, name_start, name_length);
} else {
// Nepodarilo sa načítať meno
} }
int find_student(struct student *students, int size, const char *name) {
int main() { for (int i = 0; i < size; i++) {
// Initialize array to store students if (strcmp(students[i].name, name) == 0) {
Student students[MAX_BUFFER_LENGTH]; return i; // Nájdený študent
int num_students = 0;
// Read votes from standard input
char buffer[MAX_BUFFER_LENGTH];
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
// Read number of votes and student's name
int votes;
char name[MAX_NAME_LENGTH];
if (sscanf(buffer, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n");
return 1;
}
// Store student in array
strncpy(students[num_students].name, name, MAX_NAME_LENGTH);
students[num_students].votes = votes;
num_students++;
// Check for exceeding maximum number of students
if (num_students >= MAX_BUFFER_LENGTH) {
fprintf(stderr, "Error: Too many students.\n");
return 1;
} }
} }
return -1; // Študent nenájdený
// Print error message if no records were retrieved
if (num_students == 0) {
fprintf(stderr, "Error: No records retrieved.\n");
return 1;
} }
int id = find_student(database, size, name);
if (id < 0) {
//
// Sort students by number of votes and name
qsort(students, num_students, sizeof(Student), compare_students);
// Print results
printf("Results:\n");
for (int i = 0; i < num_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0; return 0;
} }