0

I am practicing structures and arrays in c, programmed a code to take multiple student information and store it in an structure array using for loop. But when i run the code only my 0th i index runs properly and rest indexes either skips a scanf fuction or doesnt work properly.

#include<stdio.h>
#include<string.h>
struct FYSD {
    char name[100];
    int rollNo;
    float sgpa;
};
int main()
{
    int i;
    struct FYSD student[5];
    for(i = 0; i < 5; i++) {
        printf("Enter student name : ");
        gets(student[i].name);
        printf("Enter student roll no : ");
        scanf("%d",&student[i].rollNo);
        printf("Enter student sgpa : ");
        scanf("%f",&student[i].sgpa);
    }
}

Compiled code

I have no idea what is going on

  • 1
    Please post the output as text, not as an image. I suggest that you read this: [Why not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/12149471) – Andreas Wenzel Mar 08 '23 at 03:57
  • 1
    There's probably a linefeed left in the input stream after your last `scanf()`, which makes the `gets()` on the next pass return immediately. Also, you really shouldn't use `gets()`. – Dmitri Mar 08 '23 at 03:59
  • I suggest that you use [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead of `gets`. See this question for the reason: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/12149471) – Andreas Wenzel Mar 08 '23 at 04:02
  • 1
    ok so firstly c skips the scanf or gets immediately after gets or scanf respectively you either need to insert a flush scanf after gets or either make them all gets or make all of them as scanf. just change the gets statement with scanf("%s",&student[i].rollno); and your code will run fine – nischal sharma Mar 08 '23 at 07:18

0 Answers0