0
#include <stdio.h>
struct student
{
    char name[100];
    int roll;
};
int main()
{
    struct student st[2];
    for (int i=0; i<2; i++)
    {
        char c;
        printf ("\nEnter the details of student %d: \n", i+1);
        printf ("Enter the name of the student: ");
        gets (st[i].name);
        printf ("Enter the roll number of the student: ");
        scanf ("%d", &st[i].roll);
    }
    for (int i=0; i<2; i++)
    {
        printf ("\nThe details of student %d: \n", i+1);
        printf ("Name: %s", st[i].name);
        printf ("Roll no.: %d", st[i].roll);
    }
    return 0;
}

The first iteration works as intended, but in the second iteration the fgets() function skips the input and the control moves to the next input statement. I have tried using scanf() to input the name, but I want to be able to take inputs having multiple words.

The output - https://i.stack.imgur.com/OuerT.jpg

  • 1
    Does this answer your question? [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) – Chris Dodd Sep 21 '22 at 19:59
  • quick fix: replace the `gets` with `scanf(" %99[^\n]", st[i].name);` -- note the space before the `%`, it is important. – Chris Dodd Sep 21 '22 at 20:02
  • I used `fflush(stdin);` after the last `scanf()` in the for loop, and the code works perfectly now. Replacing the `gets()` with `scanf(" %99[^\n]", st[i].name);` works perfectly too. – Rounak Singh Sep 22 '22 at 07:34
  • Avoid `fflush(stdin)` as it only works on certain microsoft compilers, and has no standard defined behavior. – Chris Dodd Sep 22 '22 at 18:20
  • Would it be possible for you to elaborate what the modification in the `scanf()` function achieved and the importance of the space before the %? Thanks! – Rounak Singh Sep 22 '22 at 20:44
  • see [spaces in scanf format](https://stackoverflow.com/a/43033218/16406) – Chris Dodd Sep 22 '22 at 20:49

0 Answers0