In Below Code When I want to Enter Record of second student or >2 student .. Compiler skip Name Input and take Input for class and age .. What a problem please help me ?
First off, never use gets
. There is no way to tell it how big your buffer is, so it will cheerfully write input past the end and make the program blow up. This used to be the number one cause of remotely exploitable security holes in network servers.
Second off, never use any of the *scanf
functions either, because:
scanf
format strings are just as unsafe as gets
, notably %s
with no size modifiers.scanf
provokes undefined behavior, which means your program may crash simply because someone typed a number that was too big.scanf
, because if it fails, it does not tell you precisely where the problem characters were.For a simple task like this one, you should use fgets (or, better, getline if you have it) and convert the age to an integer with strtoul. (Age cannot be negative, so you want the unsigned version. Don't use atoi
and friends - just like *scanf
, they don't give you enough information about invalid input.)
For more complicated tasks, you should reach for lex and yacc.
The problem is common enough. Try this:
scanf("%d ", &a[i].age);
^ <--- This space will make scanf eat the remaining blanks
There are C FAQs about this:
Secondary notes:
fgets
instead.It's the scanf
. When you press ENTER
after it, the newline completes the next call to gets
.
To fix this, you can add a getchar
at the end of the loop, after the scanf
, which will consume the newline.
for(int i=0 ; i<5 ; i++)
{
printf("\n Enter Name :");
gets(a[i].Name);
printf("\n Enter Class :");
gets(a[i].Class);
printf("\n Enter Age : ");
scanf("%d" , & a[i].age);
getchar();
}