Aspis
Aspis

Reputation: 55

Counting algorithm yielding a wrong result

I want a program that counts the number of the votes of the characters R,K,A,T. When the user types $ it will stop the program.

For instance, I chose R.

I don't know why it yields the correct result minus 1 instead of the correct result. Could somebody please explain this?

The code:

#define TAUB_SYMBOL        'T'
#define KARNIN_SYMBOL      'K'
#define RABANI_SYMBOL      'R'
#define APELOIG_SYMBOL     'A'
#define BLANK_VOTE_SYMBOL  'B'
#define CESSATION_SYMBOL   '$'


int main(){
    unsigned int countT=0, countR=0, countK=0, countA=0, countBlank=0;
    unsigned int num; /  /* note that the voter index increases after an invalid votes */
    char vote;
    unsigned int valid_votes=0;
    unsigned int counter=1;
    printf("Election Ballot System\n");
    printf("----------------------\n");

    printf("Ballot secretary, please enter number of registered voters:");
    scanf("%d",&num);
    printf("Voting now commences.\n");

    while(counter<=num){
         printf("Voter %u, indicate your vote and press Enter:",counter);
         scanf("%c\n", &vote);
         if(vote==CESSATION_SYMBOL){
            counter=num+1;
         }
         else{
            switch(vote){

            case RABANI_SYMBOL:
                             countR++;
                        valid_votes++;
                        break;

            case BLANK_VOTE_SYMBOL:
                         countBlank++;
                        valid_votes++;
                        break;
            }
            counter++;
         }
    }

    printf("Voting is concluded.\n");
    printf("Election Results\n");
    printf("%d",countR);

return 0;
}

Upvotes: 1

Views: 72

Answers (2)

ekerde
ekerde

Reputation: 48

I have a solution (not the best for sure):

You can create a new char, e.g. char temp, and use to store your "\n"

Example:

scanf("%d%c",&num,&temp);

and

scanf("%c%c", &vote,&temp);

Upvotes: 0

Atul Shanbhag
Atul Shanbhag

Reputation: 636

You need to change this line

scanf("%c\n", &vote);

To

scanf("\n%c", &vote);

Since after num is inputted you are taking input a \n before every input character (R, K, A, T)

Upvotes: 1

Related Questions