Cvetelyn Ivanov
Cvetelyn Ivanov

Reputation: 59

C code crashes (no idea why)

Basically I'm a beginner coder and this is what I wrote:

#include <stdio.h>
#include <stdlib.h>

int main()
{
system("COLOR 0A");

char playerName[13];
char playerGender;
int playerAge;

printf("Please input your name and age!\nName: ");
scanf("%s", playerName);
printf("Age (from 18 to 50): ");
scanf("%d", &playerAge);

label:
if(playerAge > 18 && playerAge < 50)
{

    printf("What gender are you, M(male) or F(female): ");
    scanf("%c", playerGender);

    gender:
    if(playerGender == 'M' || playerGender == 'F'){

        printf("Okay, so your name is %s, you're %d years old and you're a %s.", playerName, playerAge, playerGender);
    }else{
        printf("Try again.\n\n"
           "What gender are you, M(male) or F(female): ");
           scanf("%c", playerGender);
           goto gender;
    }
}else{

        printf("Wrong, try again.\n"
               "Age (from 18 to 50): ");
        scanf("%d", &playerAge);
        goto label;
}


return 0;
}

When I put the required age to continue, it crashes on the scanf for the playerGender. Right after it shows me the question about my gender? Where is my mistake?

Upvotes: 3

Views: 107

Answers (2)

RA3SK
RA3SK

Reputation: 11

I am also beginner but I think that you need to write thisscanf("%s", playerName); like thisscanf("%12s", playerName);

BTW let me know if that works.

Upvotes: 0

Chris R.
Chris R.

Reputation: 572

try:

scanf("%c", &playerGender);

instead of

scanf("%c", playerGender);

as scanf takes a pointer and not a reference to the variable you are trying to fill.

Upvotes: 10

Related Questions