-1

I'm trying to code very simple code, and here it is:

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

int main()
{
    int age;
    char gender;

    printf("How old are you? \n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf("%c", &gender);

    if ((age >= 18 && gender == 'm')){
        printf("You may enter this website ");

        if (age <= 20)
        {
            printf("dude.");
        }
    }

    if ((age >= 18 && gender == 'f')) {
        printf("You may enter this website ");

        if (age <= 20)
        {
            printf("young lady.");
        }
    }
    else if (age < 18)
    {
        printf("Nothing to see here! \n");
    }
    return 0;
}

In the code above, I'm trying to use a nesting if statement. But it doesn't work, not as I wish. After I enter the age, it prints out the sentence: What is your gender? (m/f).

When the second sentence is printed out, it terminates. But I don't know why. I want the user be able to enter the gender and based on the entered gender and age it should print out a sentence.

Could you please give me a hint?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PinkP
  • 59
  • 7
  • a `switch` statement inside a `if` statement block will do... – t0mm13b Sep 24 '17 at 10:52
  • 1
    I'm voting to close this question as off-topic because similar questions were answered here 100000 times. OP did not show any debugging effort - was enough to see what is in the variable after the second scanf and **think**. Posting the question should be the last resort, not the first – 0___________ Sep 24 '17 at 11:30

3 Answers3

1

There is nothing wrong with the logic of your code, so the most likely reason for the behavior that you see is this line:

scanf("%c", &gender);

Since the line follows reading of an int, the '\n' that remains in the buffer gets assigned to gender immediately.

You can fix this by adding a space in front of %c to ignore newline:

scanf(" %c", &gender);

You can also reduce the code somewhat by combining a few checks:

if (age >= 18){
    printf("You may enter this website ");
    if (age <= 20) {
        printf("%s.\n", gender == 'm' ? "dude" : "young lady");
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Replace scanf("%c", &gender) with scanf(" %c", &gender)

klutt
  • 30,332
  • 17
  • 55
  • 95
0

This is because when you enter your age and press enter key, your age will be stored in age variable but '\n'(enter key) is still present in the buffer which will be read by the gender. So, you can do these things-

scanf("%d\n",&age)

or use

scanf("%d", &age);
getchar();
shubhamjuneja
  • 395
  • 1
  • 5
  • 16