0

fgets() is skipping and not taking input. How can I solve it? I've tried using a scanf(), but scanf() is taking input upto the first space. I want to take a input such as: Steve Jobs

#include<stdio.h>
int main()
{
    // ints
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("You are %d \n", age);

    // chars
    char grade;
    printf("Enter your grade: ");
    scanf(" %c", &grade);
    printf("You got an %c on the test \n", grade);

    // doubles
    double gpa;
    printf("Enter your gpa: ");
    scanf("%lf", &gpa);
    printf("Your gpa is %lf \n", gpa);

    // strings
    char name[20];
    printf("Enter your name:");
    fgets( name, 20, stdin);  // this line is not working
    printf("Hello %s! \n", name);


    return 0;
}
Joshua
  • 40,822
  • 8
  • 72
  • 132

1 Answers1

4

this:

scanf("%lf", &gpa);

left a newline \n in stdin

this:

fgets( name, 20, stdin);

stops inputting after consuming the newline \n

You might want to learn about character sets, similar to:

scanf( "%19[^\n]", name );

or simply calling: getchar() before calling fgets()

user3629249
  • 16,402
  • 1
  • 16
  • 17