Having an issure writing my plurality code pset.
i wanted to have my programme promt a user when they have made an invalid vote entry. and it works ok but ive found a bug while testing it:
code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.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);
void print_winner(void);
// Global Variables
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: ");
// collect all votes
for (int i = 0; i < voter_count; i++)
{
string name;
name = get_string("Vote: ");
if (strcmp(name, candidates[i].name) > 0 || strcmp(name, candidates[i].name))
{
printf("Invalid Vote, Please enter a candidates name\n");
do
{
name = get_string("Vote: ");
}
while (strcmp(name, candidates[i].name) > 0 || strcmp(name, candidates[i].name) < 0);
}
vote(name);
}
test 1 result:
~/Week_3/pset3/plurality/ $ ./plurality john
Number of voters: 2
Vote: jim
Invalid Vote, Please enter a candidates name
Vote: jim
Vote: jim
Vote: john
Vote: john
Segmentation fault
test 2 result:
~/Week_3/pset3/plurality/ $ ./plurality john
Number of voters: 2
Vote: jim
Invalid Vote, Please enter a candidates name
Vote: john
Vote: jim **PROGAM ACCEPTS INCORRECT INPUT**
Segmentation fault
I'm not too worried about the segmentation fault here as i believe this is an issue regarding the following function. However the fact my code accepts an incorrect input is an issue.
I'm wondering how it has bypassed the validity checking loops??
If anyone can help me figure out what ive missed here that would be great.