0
#include <stdio.h>

int main()
{
    char name[10];
    int birth_year;
    
    printf("Enter your name : ");
    scanf("%c",name);
    
    printf("Enter your birth year : ");
    scanf("%i",&birth_year);
    
    int age = 2020 - birth_year;
    printf("Your age is %i",age);
}

I am trying to take the value of birth_year as an input but it automatically assigns it to 0 for some reason what am I doing wrong

1 Answers1

2

In the first scanf you should read a string instead of a char, that should do it. Also, it's always good to have a whitespace before you read a char, so it resets the buffer memory.

#include <stdio.h>
int main()
{
    char name[10];
    int birth_year;

    printf("Enter your name : ");
    scanf(" %s",name);

    printf("Enter your birth year : ");
    scanf(" %d",&birth_year);

    int age = 2020 - birth_year;
    printf("Your age is %i",age);
}

    
Argie
  • 31
  • 4
  • 1
    Aside `char name[10];` is almost *certain* to overflow. Be sure to use a longer string such as `char name[100];` and restrict the input with `scanf(" %99s",name);`. These two format specifiers automatically filter leading whitespace, it is only really necessary with `%c` and `%[]`, which do not. – Weather Vane Aug 07 '20 at 20:17
  • `scanf(" %s",name);` is bad/worse than [gets](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – chux - Reinstate Monica Aug 07 '20 at 21:30