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

3
  • 2
    Use %s (not %c) for a character array (string). Commented Aug 7, 2020 at 19:55
  • 1
    Duplicated, you can see the answer here: stackoverflow.com/questions/1412513/… Commented Aug 7, 2020 at 19:56
  • @MiguelGarcía Hmm - not an obvious duplicate but I'm sure there is one somewhere. The issue here is reading a single character rather than a string. Commented Aug 7, 2020 at 19:58

1 Answer 1

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);
}

    
Sign up to request clarification or add additional context in comments.

2 Comments

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.
scanf(" %s",name); is bad/worse than gets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.