简体   繁体   中英

How to get multiple input using scanf c

#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

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

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM