Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why gets() function skips when preceded by scanf("%d")?

Tags:

c

I want to make a program which take Roll No and Full name as input and simply display it My code is . this code skip scaning value of n through gets function. Why this error occur and how to over come this?

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
 int r;
 char n[30];
 printf("enter your roll no");
 scanf("%d",&r);
 printf("enter your full name");
 gets(n);
 printf("roll no is %d ",r);
 printf("name is %s ",n);
 getch();
 }

while the below code scan the first gets value and skips the second one.

#include<stdio.h>
#include<conio.h>
void main()
{
 int r;
 char n[30], f[30];
 printf("enter your roll no");
 scanf("%d",&r);
 printf("enter your full name");
 gets(n);
 printf("enter your full name of your father ");
 gets(f);
 printf("roll no is %d ",r);
 printf("name is %s ",n);
 printf("father name is %s ",f);
 getch();
 }
like image 799
Azad Hussain Avatar asked Jun 29 '26 10:06

Azad Hussain


1 Answers

The simple solution for the problem is to add fflush(stdin); between scanf(); and gets();

#include<stdio.h>
#include<conio.h>
void main()
{
    int r;
    char n[30],fn[30];
    clrscr();
    printf("\nEnter roll ");
    scanf("%d",&r);
    fflush(stdin);
    printf("\nEnter name ");
    gets(n);
    printf("\nEnter father name ");
    gets(fn);

    printf("\n\nRoll %d",r);
    printf("\nname %s",n);
    printf("\nfather name %s",fn);
    getch();
}
like image 185
Azad Hussain Avatar answered Jun 30 '26 22:06

Azad Hussain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!