0

Here's the code:

#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;

// 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)
{
    for (int i = 0; candidate_count > i; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            candidates[i].votes++;
            return true;
        }
    }

    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO

    // Print candidate(s) with the most votes

    // Loop through all the votes, compare which is higher, and the highest one gets printed out

    int tieCount = 0;

    for (int i = 0; candidate_count > i; i++)
    {
        for (int j = 0; candidate_count > j; j++)
        {
            // Tests for equality

            int equalComp = j;

            if(equalComp == i)
            {
                equalComp += 1;
            }

            if (candidates[i].votes == candidates[equalComp].votes) // Compares to the if numbers are equal
            {
                tieCount++;
                printf("%s\n", candidates[j].name);

                if (tieCount >= candidate_count)
                {
                    return;
                }
            }

            if (equalComp == candidate_count) // Breaks if the comparision number overshots the loop
            {
                return;
            }
        }

        for (int j = 0; candidate_count > j; j++)
        {
            // Tests for greater than

            int greaterComp = j;

            if(greaterComp == i)
            {
                greaterComp += 1;
            }

            if (candidates[i].votes > candidates[greaterComp].votes) // Compares to the if numbers are greater than
            {
                printf("%s\n", candidates[i].name);

                return;
            }

            if (greaterComp == candidate_count) // Breaks if the comparision number overshots the loop
            {
                return;
            }
        }
    }

    return;
}

And here's the check50 output:

:) 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 function did not print winner of election
:) print_winner prints multiple winners in case of tie
:) print_winner prints all names when all candidates are tied

I don't understand why it doesn't print Charlie as the winner, any advice? I've been stuck on this for about two days now, and i finally got it to work as what i understand the given specifications, and i dont really understand why it only seems to get stuck on Charlie.

Thanks so much for your help, much love :D

  • 1
    "I don't understand why it doesn't print Charlie as the winner" -- Have you tried running your code line by line in a debugger while monitoring the values of all variables? That should allow you to understand exactly what is going on in your program. If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel Apr 15 '22 at 11:49
  • 1
    Note that CS50 has its own debugger, called [debug50](https://cs50.harvard.edu/ap/2021/curriculum/x/references/bugs_and_debugging.pdf). I don't know it though, so I don't know if it is worth recommending. I believe it is only intended for people using the CS50 IDE. – Andreas Wenzel Apr 15 '22 at 11:49
  • @AndreasWenzel Thank you so much for the more informative answer, I really appreciate it :D I'll update the post if I figure out what was the problem :D – IncognitoSpeedy Apr 15 '22 at 12:12
  • @AndreasWenzel The "How to debug small programmes" was absolutely amazing, and I greatly appreciate it. I love that it's so indirectly shoots shots at me for my poorly phrased questions :D But genuinely, thank you for the lesson, and I'm sure I will apply my newfound knowledge in so many cases :D Have a great day you lovely person, and I hope one day our rubberducks can meet! :D – IncognitoSpeedy Apr 19 '22 at 10:36
  • 1
    I am pleased that you found my links useful. In the article "How to debug small programs", it was mentioned that all languages have a mechanism for assertions, but they were only mentioned for the language C#, not C. In case you are wondering what they are in C, I will tell you: In C, when you `#include `, you can use the [`assert`](https://en.cppreference.com/w/c/error/assert) macro, for example like this: `assert( my_pointer != NULL );` That way, the program will immediately abort with an error message if the assertion condition is false (unless you deactivate assertions). – Andreas Wenzel Apr 19 '22 at 19:02
  • 1
    In the case of your question, I believe that running your program line by line in a debugger while monitoring the values of all variables would be the best option to understand what is going wrong in your program. Have you been able to do that? Have you been able to find the problem? – Andreas Wenzel Apr 19 '22 at 19:24
  • I only managed to get time to go on with solving the problem today,medical stuff and life kinda got in the way.I'm working on it right now, and so far, I have a slight suspicion as to what could be the problem, I did go line by line debugging, and now I'm writing down what i want my programme to do on a piece of paper in hopes of understanding whats happening better :D My suspicion of what the culprit is, it makes sure it does not compare the a value with the same value, but it in doing it that way, it prevents in from going back to the previous value, its a poor explanation. Thanks though :D – IncognitoSpeedy Apr 20 '22 at 08:41
  • Which debugger are you using? Are you using "debug50" together with the CS50 IDE? Or are you using some other [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment)? Are you coping well with handling the debugger? You should be mainly using the "step into" and "step over" buttons of the debugger (the exact names of the buttons may differ depending on the debugger). – Andreas Wenzel Apr 20 '22 at 13:12

0 Answers0