Search code examples
cstringscanffgets

How to make fgets() ignore a \n at beginning?


I have below C code.

struct student
{
    int rollNumber;
    char name[20];
    char department[20];
    char course[20];
    int yearOfJoining;
};

int main()
{
    // Creating a 'student' variable.
    struct student s;

    // Take the info of student from keyboard

            printf("Student \n-------------------\n");
            printf("Roll no: ");
            scanf("%d",&s.rollNumber);
            printf("Name: ");
            fgets(s.name, 20, stdin);
            //scanf("%s",&s.name);
            printf("Department: ");
            fgets(s.department, 20, stdin);
            //scanf("%s",&s.department);
            printf("Course: ");
            fgets(s.course, 20, stdin);
            //scanf("%s",&s.course);
            printf("Year of joining: ");
            scanf("%d",&s.yearOfJoining);

   return 0;
}

However when I compile and run this code below happens.

-bash-4.1$ ./a.out
Student
-------------------
Roll no: 1
Name: Department: ECE
Course: CE
Year of joining: 2006
-bash-4.1$

You can see that first fgets() doesn't not wait for the string input from keyboard.

I am sure this is because fgets() is taking the \n which was in the input buffer after I gave the roll number and pressed ENTER.

When I try with scanf(which is commented out in the code above) instead of fgets, it works fine. However I want to use fgets(), not scanf().

Something like this happened to me while getting a character from keyboard (%c) yesterday, in which case i could give a %c (with a space before %c) to make scanf() ignore the \n. This problem was discussed here.

However, I can't do something like that with fgets() as i don't specify (%s). (Also, surprisingly I didn't have to give a space before %s for scanf(), which i initially thought I needed to).


Solution

  • Ok, the original idea does not seem to work, so another try:

    scanf("%d",&s.rollNumber);
    printf("Name: ");
    fgets(s.name, 20, stdin); /* capture the new line */
    fgets(s.name, 20, stdin);
    

    Original idea: Simply tell scanf to also capture the newline:

    scanf("%d\n",&s[i].rollNumber);