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); 
        }
    }
}

2 Answers 2

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).

0

The issue is that you used voter_count as the condition. Change it to candidate_count it'll work fine. You should iterate through the loop candidate_count number of times. Your program can have a 1000 voter_count.. But we're comparing the votes of all the candidates we have.

You must log in to answer this question.

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