This commit is contained in:
Tančáková 2024-03-20 14:52:38 +01:00
parent 4fcaed905f
commit f44d5266fb

View File

@ -5,36 +5,47 @@
#define MAX_STUDENTS 100 #define MAX_STUDENTS 100
#define MAX_NAME_LENGTH 100 #define MAX_NAME_LENGTH 100
// Structure to hold student information (name and votes)
typedef struct { typedef struct {
char name[MAX_NAME_LENGTH]; char name[100];
int votes; int votes;
} Student; } Student;
// Function to compare two students based on their votes and names
int compare_students(const void *a, const void *b) { int compare_students(const void *a, const void *b) {
const Student *student1 = (const Student *)a; const Student *student1 = (const Student *)a;
const Student *student2 = (const Student *)b; const Student *student2 = (const Student *)b;
// Sort by number of votes in descending order
if (student1->votes != student2->votes) { if (student1->votes != student2->votes) {
return student2->votes - student1->votes; return student2->votes - student1->votes;
} else { } else {
// If votes are equal, sort lexicographically by name
return strcmp(student1->name, student2->name); return strcmp(student1->name, student2->name);
} }
} }
int main() { int main() {
char line[256]; char line[256];
Student students[MAX_STUDENTS]; Student students[100];
int total_students = 0; int total_students = 0;
// Read votes from standard input
while (fgets(line, sizeof(line), stdin)) { while (fgets(line, sizeof(line), stdin)) {
int votes; int votes;
char name[MAX_NAME_LENGTH]; char name[100];
// Parse votes and name from input line
if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) { if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n"); fprintf(stderr, "Error: Invalid input format.\n");
return 1; return 1;
} }
// Check if the votes are positive
if (votes <= 0) {
fprintf(stderr, "Error: Invalid number of votes.\n");
return 1;
}
// Find if the student is already in the list
int found = 0; int found = 0;
for (int i = 0; i < total_students; i++) { for (int i = 0; i < total_students; i++) {
if (strcmp(students[i].name, name) == 0) { if (strcmp(students[i].name, name) == 0) {
@ -44,6 +55,7 @@ int main() {
} }
} }
// If student not found, add to the list
if (!found) { if (!found) {
if (total_students >= MAX_STUDENTS) { if (total_students >= MAX_STUDENTS) {
fprintf(stderr, "Error: Too many students.\n"); fprintf(stderr, "Error: Too many students.\n");
@ -55,13 +67,16 @@ int main() {
} }
} }
// Sort the list of students based on votes and names
qsort(students, total_students, sizeof(Student), compare_students); qsort(students, total_students, sizeof(Student), compare_students);
printf("Outcome:\n"); // Print the outcome
printf("Results:\n");
for (int i = 0; i < total_students; i++) { for (int i = 0; i < total_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name); printf("%d %s\n", students[i].votes, students[i].name);
} }
return 0; return 0;
} }