I used fgets()
and gets()
also for getting a string as input inside a loop. In the first execution, it worked properly but in the second time, it skips the inputting step and straight away goes to the next line.
#include<stdio.h>
#include<conio.h>
struct student
{
int roll,m[3];
float avg;
char name[30];
}s[5];
void main()
{
int i;
clrscr();
printf("Enter thr student details:");
for(i=0;i<5;i++)
{
printf("\nstudent[%d] name:",i+1);
fgets(s[i].name,30,stdin);
printf("student[%d] register number: ",i+1);
scanf("%d",&s[i].roll);
printf("student[%d] marks:\n",i+1);
scanf("%d%d%d",&s[i].m[0],&s[i].m[1],&s[i].m[2]);
s[i].avg=(s[i].m[0]+s[i].m[1]+s[i].m[2])/3;
}
printf("-----------------------------------------------------------");
printf("\n NAME REG.NO AVERAGE");
printf("\n-----------------------------------------------------------");
printf("\n DISTINCTION");
for(i=0;i<5;i++)
if(s[i].avg>74)
printf("\n%-20s%-10d%.2f",s[i].name,s[i].roll,s[i].avg);
printf("\n FIRST CLASS");
for(i=0;i<5;i++)
if((s[i].avg<74)&&s[i].avg>50)
printf("\n%-20s%-10d%.2f",s[i].name,s[i].roll,s[i].avg);
printf("\n FAIL");
for(i=0;i<5;i++)
if(s[i].avg<50)
printf("\n%-20s%-10d%.2f",s[i].name,s[i].roll,s[i].avg);
getch();
}
as told by @chux , scanf
leaves '\n' in the stdin
( memory buffer ) , and fgets()
takes value until there is a '\n' in the buffer , in order to clear the buffer the statement fflush(stdin);
is used before the fgets()
statement