0

Every example I try myself works perfectly fine but once I check50 it, I get error messages for not printing one,two, or all three winners. I saw some people having format issues with spaces, but I donĀ“t think I have any of those.

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;
int voter_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
  bool validvote = false;
   for (int i = 0; i < candidate_count; i++)
    if (strcmp(name,candidates[i].name)==0)
    {
        candidates[i].votes++; 
        validvote = true;  
    }
    return validvote;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
   int biggestvalue = 0; 
   
   for (int i = 0; i < voter_count; i++)
    {
    if (candidates[i].votes > biggestvalue)
        {
           biggestvalue = candidates[i].votes;
        }
    }
    for (int i = 0; i < voter_count; i++)
    {
        if (candidates[i].votes == biggestvalue)
        {
           printf("%s\n", candidates[i].name); 
        }
    }
}
1

Try this election: 3 candidates: a, b, c and 2 voters who vote for c. It reports a and b as (tied) winners. That's because c's votes are not considered in the first for (int i = 0; i < voter_count; i++), because voter_count is 2 and candidate c is index 2. (Neither is candidate c considered in the second for (int i = 0; i < voter_count; i++), for the same reason).

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .