0

Attached are my two functions. The code did not print winner for two inputs and also did not print all names in case of tie.

// Update vote totals given a new vote
bool vote(string name)
{
    // TODO
    int counter = 0;
    int index;
    for(int i = 0; i < candidate_count; i++)
    {

        if(strcmp(name, candidates[i].name) == 0)
        {
            counter = 1;
            index = i;
            break;
        }
        else
        {
            counter = 0;
        }
    }
    if (counter == 1)
    {
        candidates[index].votes++;
        return true;
    }
    else
    {
        return false;
    }
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    int max = candidates[0].votes;
    int c1;
    int c2;
    string winner = candidates[0].name;
    for(int j = 1; j < candidate_count; j++)
    {
        c1 = candidates[j].votes;
        if(max < c1)
        {
            max = c1;
            winner = candidates[j].name;
        }
    }
    printf("%s\n", winner);
    //To print multiple winners 
    for (int k = 0; k < candidate_count; k++)
    {
        c2 = candidates[k].votes;
        if (max == c2 && candidates[k].name != winner)
        {
            printf("%s", candidates[k].name);
        }
    }
    printf("\n");
    return;
}

1 Answer 1

1

You may be happy (or frustrated) to know that the errors in your code are relatively trivial.

I ran your code through debug50 and set a breakpoint at the print_winner function. It looks like you have some new-line issues in the second loop of print_winner:

for (int k = 0; k < candidate_count; k++)
    {
        c2 = candidates[k].votes;
        if (max == c2 && candidates[k].name != winner)
        {
            printf("%s", candidates[k].name);
        }
    }
    printf("\n");
    return;

So when it goes to print multiple names, they end up looking like this:

Alice
BobCharlie

Check50 wants them to look like this:

Bob
Alice
Charlie

You must log in to answer this question.

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