I have finished the plurality program for pset3 of cs50, but upon running check50 on my code, I receive the following error directed towards the print_winner function:
:) plurality.c exists
:) plurality compiles
:) vote returns true when given name of first candidate
:) vote returns true when given name of middle candidate
:) vote returns true when given name of last candidate
:) vote returns false when given name of invalid candidate
:) vote produces correct counts when all votes are zero
:) vote produces correct counts after some have already voted
:) vote leaves vote counts unchanged when voting for invalid candidate
:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:) print_winner identifies Charlie as winner of election
:( print_winner prints multiple winners in case of tie
print_winner function did not print both winners of election
:) print_winner prints all names when all candidates are tied
Even though my function indeed prints multiple winners in case of a tie (and I tested it multiple times for various scenarios), this error still persists, and I'm not sure why. Can someone please examine my code below and elaborate on what is wrong with the code? (I'm sorry if it's very messy/ineffecient - I took a while to write it because it took me a while to figure out how to print multiple winners):
void print_winner(void)
{
int j = 0;
int max = candidates[0].votes;
int competitor;
int competitor2;
string winner = candidates[0].name;
// loop over all candidates + determine candidate with most votes (max)
// + name candidate with most votes (winner)
for (j = 1; j < candidate_count; j++)
{
competitor = candidates[j].votes;
if (max < competitor)
{
max = competitor;
winner = candidates[j].name;
}
}
// loop over candidates again to determine if multiple winners + print winner/winners
for (int f = 0; f < candidate_count; f++)
{
competitor2 = candidates[f].votes;
if (max == competitor2 && candidates[f].name != winner)
{
for (int i = 0; i < candidate_count; i++)
{
printf("%s\n", candidates[i].name);
}
return;
}
}
printf("%s\n", winner);
return;
}