fgets function not taking user input

46 views Asked by At

I want to input my fullname but the program finishes only after getting name input only. Why is it ignoring to read fullname input and why is it outputting "Your name is" on the final output? Please explain like I'm 5 year old.

#include <stdio.h>

int main()
{
    /* some codes do not work as expected. How so? */

    int age;
    printf("Enter your age: ");
    /* asking which type of data we want from user */
    scanf("%d", &age);
    printf("You are %d years old \n", age);

    double gpa;
    printf("Enter your gpa: ");
    scanf("%lf", &gpa);
    /* what is lf? */
    printf("Your gpa is %lf \n", gpa);
    
    char name[20];
    printf("Enter your name: ");
    /* no need for ambersand */
    scanf("%s", name);
    printf("Your name is %s \n", name);
    /* issue with scanf is that everything after scan is ignored */
    
    char fullname[20];
    printf("Enter your full name: ");
    /* fgets does take space included input no need for ambersand */
    fgets(fullname, 20, stdin);
    printf("Your name is %s \n", fullname);
    /* issue with scanf is that everything after scan is ignored */
    return 0;
}

The output I got was

Enter your age: 5
You are 5 years old 
Enter your gpa: 3.6
Your gpa is 3.600000 
Enter your name: papa
Your name is papa 
Enter your full name: Your name is 

I tried compiling and ran it. If we have fullname input only, then the program runs as expected but if we mix this with scanf it causes a problem. I'd like to understand why exactly that is, why there is this issue of not taking further input from user.

0

There are 0 answers