0

This is a program to enter the details like name and address of students and display them to understand functions and structures but faced a problem. The first gets of the input function is not working and taking any input. Where have I gone wrong and what can be done to make it work?

   #include <string.h>
   struct student
    {
        long int roll;
        char name[100];
        char address[100];
        int age;
        int avg_marks;
    }std[3];
    void input()
    {
        int i;
        for (i=0;i<3;i++)
        {
            printf("Enter the details of %dth student:\n",i+1);
            printf("ROLL NO.: ");
            scanf("%ld",&std[i].roll);
            printf("NAME: ");
            gets(std[i].name); //Not working//
            printf("ADDRESS: ");
            gets(std[i].address);
            printf("AGE: ");
            scanf("%d",&std[i].age);
            printf("AVERAGE MARKS: ");
            scanf("%d",&std[i].avg_marks);
            printf("\n");
        }
    }
    void print()
    {
        int i;
        for (i=0;i<3;i++)
        {
            printf("Details of %dth student:\n",i+1);
            printf("ROLL NO.: %ld\n",std[i].roll);
            printf("NAME: ");
            puts(std[i].name);
            printf("\nADDRESS: ");
            puts(std[i].address);
            printf("\nAGE: %d\n",std[i].age);
            printf("AVERAGE MARKS: %d",std[i].avg_marks);
            printf("\n");
       }
    } 
    void main()
    {
        void input();
        void print();
        input();
        print();
    }```
  • 1
    Please see [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) and [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) and read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Weather Vane Apr 17 '20 at 09:15
  • I believe `gets` may be the only library function that's ever been deprecated and removed from the ISO C standard. That should tell you something about the wisdom, or otherwise, of using it :-) – paxdiablo Apr 17 '20 at 09:18
  • The function `char *getwd(char *buf)` is also deprecated for the same reason (potential buffer overflow) but this one was not part of the standard C library. – Weather Vane Apr 17 '20 at 09:25
  • Never ever use `gets()`, use `fgets()` instead. Click on the last link in the first comment for more information. If your teacher insist on that you need to use it, he/she shall be fired. – RobertS supports Monica Cellio Apr 17 '20 at 09:29

0 Answers0