Search code examples
carraysstructuregets

Error in getting input in structure using gets()


I am making a program to take input in teacher structure but there is unknown run time error , here is the code -

#include <stdio.h>
#include <conio.h>

struct Teacher
{
 char Name[30];
 char Qualifications[20];
 int experience_year;
}th[10];

void teacher()
{    
 int t,i;
 printf("Enter how many teachers are in department\n");
 scanf("%d",&t);
 for(i=1;i<=t;i++)
 {       
   printf("Enter name of teacher : ");
   gets(th[i].Name);
   printf("Enter qualification of teacher : ");
   gets(th[i].Qualifications);
   printf("Enter experience_year of teacher : ");
   scanf("%d",&th[i].experience_year);
 }
 for(i=1;i<=t;i++)
 {
   printf("Details of %d teacher\n",i);
   printf(th[i].Name);
   printf(" ");
   printf(th[i].Qualifications);
   printf(" ");
   printf("%d",th[i].experience_year);
   printf("\n");
 }
}   
int main()
 {
   teacher();
   return 0;
 }

Output is -

Enter number of teacher
1
Enter teachers name : Enter qualification of teacher :

How to get teacher's name(input).. and what is the error ?


Solution

  • Use this:

    getchar();
    

    before

     gets(th[i].Name);
    

    to consume leading whitespaces and newlines, which were left in the buffer due to previous statements.

    Also, I would recommend fgets, which is safer than gets as:

    fgets(th[i].Name,30,stdin);
    

    and

    fgets(th[i].Qualifications,20,stdin);
    

    Why gets is dangerous