#include #include #include #define MAX_NAME_LENGTH 100 #define MAX_BUFFER_LENGTH 256 // Structure to store student information typedef struct { char name[MAX_NAME_LENGTH]; int votes; } Student; // Comparison function for sorting students by votes and name int compare_students(const void *a, const void *b) { const Student *student_a = (const Student *)a; const Student *student_b = (const Student *)b; // First compare by number of votes if (student_a->votes != student_b->votes) { return student_b->votes - student_a->votes; // Sort in descending order } // If votes are tied, compare lexicographically by name return strcmp(student_a->name, student_b->name); } int main() { // Initialize array to store students Student students[MAX_BUFFER_LENGTH]; 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; } } // Print error message if no records were retrieved if (num_students == 0) { fprintf(stderr, "Error: No records retrieved.\n"); return 1; } // 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; }