0

When I run the following code, the name and roll can be entered but course name can not be read, it passes directly to marks. I understood the problem. fgets function read a space so it passes to mark, but where is the space to read. I solved the problem by writing scanf("\n") which is not a way ı want to perform. Do you have any idea why fgets reads space?

#include <stdio.h>

#define SIZE 50

struct student {
    char name[SIZE];
    int roll;
    char courseName[SIZE];
    float marks;
} stu1;

//struct student stu1;

int main() {
    printf("Please Enter the student information:\n\n");
    
    printf("Enter name: ");
    fgets(stu1.name, SIZE, stdin);
    printf("Enter roll number: ");
    scanf("%d", &stu1.roll);
    printf("Enter the course name: ");
    //scanf("\n");
    fgets(stu1.courseName, SIZE, stdin);
    printf("Enter marks: ");
    scanf("%f", &stu1.marks);

    printf("\nThe information you you entered:\n\n");
    printf("Name: %s", stu1.name);
    printf("Roll number: %d\n", stu1.roll);
    printf("Course name: %s", stu1.courseName);
    printf("Marks: %.1f", stu1.marks);

    return 0;
}
etly
  • 31
  • 1
  • 1
  • 2

0 Answers0