0

Hello I would like to ask why my function does not update votes for candidates. For example I vote for Bob 3 times and than my program prints that Bob has 0 votes.

Function:

bool check_vote(char vote_name [])
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, vote_name) == 0)
        {
            candidates[i].votes++;
            return true;
        }
    }
    return false;
}

Whole code:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool check_vote(char vote_name []);

int candidate_count = 3;

struct person
{
    char name[50];
    int votes;
}candidates[3];


int main(void)
{
    strcpy(candidates[0].name, "Alice");
    candidates[0].votes = 0;

    strcpy(candidates[1].name, "Charlie");
    candidates[1].votes = 0;

    strcpy(candidates[2].name, "Bob");
    candidates[2].votes = 0;


    int i = 1;
    int voters;
    char vote_name[7];
    printf("How many voters are here: ");
    scanf("%i", &voters);
    fgetc(stdin);
    for (voters; voters > 0; voters--)
    {
        printf("Vote %i: ", i++);
        fgets(vote_name, sizeof vote_name, stdin);
        check_vote(vote_name);
    }
    printf("%i", candidates[2].votes);
    return 0;
}

bool check_vote(char vote_name [])
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, vote_name) == 0)
        {
            candidates[i].votes++;
            return true;
        }
    }
    return false;
}
themm1
  • 137
  • 2
  • 10
  • 1
    `fgets` also reads the `\n`, remove it before calling `check_vote`. – mch Nov 06 '20 at 10:03
  • Could be easily debugged and identified as a problem not with modifying global variables, but instead with `vote_name`, by printing `vote_name` with quotes around it, and is a dupe anyway. – underscore_d Nov 06 '20 at 10:13

0 Answers0