pvjc24/cv5/program.c

89 lines
2.4 KiB
C
Raw Normal View History

2024-03-13 09:55:11 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
2024-03-13 10:10:55 +00:00
// Structure to hold candidate information
2024-03-13 09:55:11 +00:00
typedef struct {
char name[MAX_NAME_LENGTH];
int votes;
} Candidate;
2024-03-13 10:10:55 +00:00
// Comparator function for qsort
2024-03-13 09:55:11 +00:00
int compare_candidates(const void *a, const void *b) {
const Candidate *candidate_a = (const Candidate *)a;
const Candidate *candidate_b = (const Candidate *)b;
2024-03-13 10:10:55 +00:00
// Sort by total votes in descending order
2024-03-13 09:55:11 +00:00
if (candidate_a->votes != candidate_b->votes) {
return candidate_b->votes - candidate_a->votes;
} else {
// If votes are tied, sort lexicographically by name
return strcmp(candidate_a->name, candidate_b->name);
}
}
int main() {
Candidate candidates[100]; // Assuming no more than 100 candidates
int num_candidates = 0;
// Read votes from standard input
while (1) {
int votes;
char name[MAX_NAME_LENGTH];
// Try to read votes and name
2024-03-13 10:10:55 +00:00
if (scanf("%d ", &votes) != 1) {
2024-03-13 09:55:11 +00:00
if (feof(stdin)) {
break; // End of input
} else {
printf("Error: Failed to read vote.\n");
return 1;
}
}
2024-03-13 10:10:55 +00:00
// Read candidate name
if (fgets(name, MAX_NAME_LENGTH, stdin) == NULL) {
printf("Error: Failed to read candidate name.\n");
return 1;
}
// Remove trailing newline character
name[strcspn(name, "\n")] = '\0';
2024-03-13 09:55:11 +00:00
// Check if the candidate already exists
int found = 0;
for (int i = 0; i < num_candidates; i++) {
if (strcmp(candidates[i].name, name) == 0) {
candidates[i].votes += votes;
found = 1;
break;
}
}
// If the candidate is not found, add a new candidate
if (!found) {
if (num_candidates >= 100) {
printf("Error: Too many candidates.\n");
return 1;
}
strcpy(candidates[num_candidates].name, name);
candidates[num_candidates].votes = votes;
num_candidates++;
}
}
// Sort the candidates
qsort(candidates, num_candidates, sizeof(Candidate), compare_candidates);
// Print the outcome
printf("Outcome:\n");
for (int i = 0; i < num_candidates; i++) {
printf("%d %s\n", candidates[i].votes, candidates[i].name);
}
return 0;
}