In the code below, strings in argv never matches the user input strings.
For example, if I execute a code with line ./plurality Alice Bob
, the names in argc are correctly transferred to the candidates
array, but they just never match with the strings that is received later in the program. (Unnecessary part of the programs were removed, for the sake of readability.)
#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[])
{
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
printf("%s ", candidates[i].name);
candidates[i].votes = 0;
}
printf("\n");
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");
}
}
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].name == name)
{
candidates[i].votes++;
return true;
}
}
return false;
}
This is driving me crazy, any kind of help would be appreciated.