This program is for counting the plurality for a list of candidates, Check Description for more info, The program works like this:
- Enter the candidate's name as an argument when running the program for example:
./plurality John Jack Tom Timara
- The program will ask you to enter the Number of voters
- The program will ask you for your vote, It should be one of the candidates' names (Case Sensitive).
- After you enter the candidate's name the program will ask you again for your vote depend on your Number of voters.
- The program will output the winning candidate. (Could be more than one candidate if they are equal)
What is my problem?
Let's say when I enter Number of voters: 6
and vote 3 times for John
and 3 times for Jack
the output will be:
The winner is: John,
But if I vote 3 times for John
and 3 times for Tom
or Timara
the output will be:
The winner is: John, Tom
The program doesn't work correctly if the first candidate and the second have an equal amount of votes and I don't know why! Here is My 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)
{
[snip] return exist;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
[snip]
}
vote
runs I'll assume that the candidate that I'm looking for does not exist so I create a newbool
variable calledexist
and set its default value tofalse
. Next, I create a loop to look at each candidate incandidates[i].name
, to do that you need to use a function calledstrcmp()
, you can learn more about it from here. Thestrcmp()
function compares two strings if they are equal the return value will be0
, (continue in the next comment).if (strcmp(name, candidates[i].name) == 0)
if its true I'll update thecandidate[i].votes
and add1
to it, then I'll update theexist
bool to equaltrue
and then I'll out from this loop by usingbreak
so I don't waste more time searching for the candidate. then at the end of the function I'llreturn
the currentexist
value.