This commit is contained in:
Tančáková 2024-03-13 11:10:55 +01:00
parent d8cc432763
commit ea0f234a7f

View File

@ -4,16 +4,18 @@
#define MAX_NAME_LENGTH 100 #define MAX_NAME_LENGTH 100
// Structure to hold candidate information
typedef struct { typedef struct {
char name[MAX_NAME_LENGTH]; char name[MAX_NAME_LENGTH];
int votes; int votes;
} Candidate; } Candidate;
// Comparator function for qsort
int compare_candidates(const void *a, const void *b) { int compare_candidates(const void *a, const void *b) {
const Candidate *candidate_a = (const Candidate *)a; const Candidate *candidate_a = (const Candidate *)a;
const Candidate *candidate_b = (const Candidate *)b; const Candidate *candidate_b = (const Candidate *)b;
// Sort by number of votes in descending order // Sort by total votes in descending order
if (candidate_a->votes != candidate_b->votes) { if (candidate_a->votes != candidate_b->votes) {
return candidate_b->votes - candidate_a->votes; return candidate_b->votes - candidate_a->votes;
} else { } else {
@ -32,7 +34,7 @@ int main() {
char name[MAX_NAME_LENGTH]; char name[MAX_NAME_LENGTH];
// Try to read votes and name // Try to read votes and name
if (scanf("%d %99s", &votes, name) != 2) { if (scanf("%d ", &votes) != 1) {
if (feof(stdin)) { if (feof(stdin)) {
break; // End of input break; // End of input
} else { } else {
@ -41,6 +43,15 @@ int main() {
} }
} }
// 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';
// Check if the candidate already exists // Check if the candidate already exists
int found = 0; int found = 0;
for (int i = 0; i < num_candidates; i++) { for (int i = 0; i < num_candidates; i++) {