0

Task is to have people type in their votes for the candidates given in the command line, then the most voted candidate wins. I only need to and am allowed to write code for the last two function prototypes.

So for now, the plurality code works fine...until the voter types an invalid name, then the program stops with a "segmentation fault". I don't get what causes this exactly. What should I do to fix this?

I had a previous code version, where this doesn't happen. So when a false name is typed in, it will print out "Invalid vote" as it should be. However, even then there was the problem that there was no more prompts left, so if there are 3 voters, then after 3 prompts the program ends. That's fine if everyone types in correctly. But if there is one invalid vote, then the program would only have two valid vote inputs before it ends.

Then about the "print winner" function, is there any function in CS50 that allows me to pick the largest candidates[i].votes or does it have to be solved differently...?

Thanks!

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

// Max number of candidates
// "the MAX here is a constant (equal to 9) that you can use now"
#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;

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

    int 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)
{
    // TODO
    for (int h = 0; h < MAX; h++)
    {
        for (int i = 0; i < MAX; i++)
        {
            if (strcmp(candidates[i].name, name) == 0)
            {   
                printf("Match\n");
                candidates[i].votes++;
                return true;
            }
        }
        return false;
    }
    return 0;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    printf("The winner is...");
    return;
}

You must log in to answer this question.

Browse other questions tagged .