pvjc24/cv5/program.c

72 lines
1.9 KiB
C
Raw Normal View History

2024-03-13 09:55:11 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-20 12:33:29 +00:00
// Structure to hold student information (name and votes)
2024-03-13 09:55:11 +00:00
typedef struct {
2024-03-20 12:33:29 +00:00
char name[100];
2024-03-13 09:55:11 +00:00
int votes;
2024-03-20 12:33:29 +00:00
} Student;
2024-03-13 09:55:11 +00:00
2024-03-20 12:33:29 +00:00
// Function to compare two students based on their votes and names
int compare_students(const void *a, const void *b) {
const Student *student1 = (const Student *)a;
const Student *student2 = (const Student *)b;
// Sort by number of votes in descending order
if (student1->votes != student2->votes) {
return student2->votes - student1->votes;
2024-03-13 09:55:11 +00:00
} else {
2024-03-20 12:33:29 +00:00
// If votes are equal, sort lexicographically by name
return strcmp(student1->name, student2->name);
2024-03-13 09:55:11 +00:00
}
}
int main() {
2024-03-20 12:33:29 +00:00
char line[256];
Student students[100];
int total_students = 0;
2024-03-13 09:55:11 +00:00
// Read votes from standard input
2024-03-20 12:33:29 +00:00
while (fgets(line, sizeof(line), stdin)) {
2024-03-13 09:55:11 +00:00
int votes;
2024-03-20 12:33:29 +00:00
char name[100];
// Parse votes and name from input line
if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n");
2024-03-13 10:10:55 +00:00
return 1;
}
2024-03-20 12:33:29 +00:00
// Find if the student is already in the list
2024-03-13 09:55:11 +00:00
int found = 0;
2024-03-20 12:33:29 +00:00
for (int i = 0; i < total_students; i++) {
if (strcmp(students[i].name, name) == 0) {
students[i].votes += votes;
2024-03-13 09:55:11 +00:00
found = 1;
break;
}
}
2024-03-20 12:33:29 +00:00
// If student not found, add to the list
2024-03-13 09:55:11 +00:00
if (!found) {
2024-03-20 12:33:29 +00:00
strcpy(students[total_students].name, name);
students[total_students].votes = votes;
total_students++;
2024-03-13 09:55:11 +00:00
}
}
2024-03-20 12:33:29 +00:00
// Sort the list of students based on votes and names
qsort(students, total_students, sizeof(Student), compare_students);
2024-03-13 09:55:11 +00:00
// Print the outcome
printf("Outcome:\n");
2024-03-20 12:33:29 +00:00
for (int i = 0; i < total_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
2024-03-13 09:55:11 +00:00
}
return 0;
}
2024-03-20 12:33:29 +00:00