Why gets() function skips when preceded by scanf("%d")? - 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();
}

The code DOES NOT skip scanning the value of 'n'.
I believe that when you run the program, you enter the Roll No and then press the ENTER key on your keyboard.
This is the cause.
As soon as you press the ENTER key, the escape sequence '\n' is saved in the array n. Your gets() command is executing perfectly.
In the second case, the variable 'n' stores the escape sequence and the next variable 'f' takes the string you enter next.
To make your code work just enter your scanf statement like this:-
scanf("%d ",&r);
Notice the space after %d.
Try this code-
#include<stdio.h>
int main(void)
{
int r;
char n[30], f[30];
printf("Enter your roll no");
scanf("%d ",&r); // I have inserted a space after %d
printf("Enter your full name");
gets(n);
printf("Enter your full name of your father ");
gets(f);
printf("\nRoll no is %d ",r);
printf("\nName is %s ",n);
printf("\nFather name is %s ",f);
return 0;
}
TIP:- You must try not to use gets() and puts()
You can read more about it here.

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();
}

Using scanf instead of gets will solve your problem:
scanf("%s", n); // Read in your name
Please note that when reading in any string like this you should use safe functions that are passed the length of the string (for example scanf_s from MSDN).

I don't know why it gets skipped but what you could do to avoid any other confusion like fflush(stdin) or fgets etc etc.
Just use gets(string) on the next line. So when it skips the first gets command it goes onto the other one.
Try that
Cheers,
;)

I just had the same problem two hours ago, but to solve this situation easily, all you have to fo is to add a "getchar()" after the "scanf()" and before the "gets()", so that the extra "\n" goes to the "getchar()" and you can type as you want in the next "gets()".

I was also facing the same problem as mentioned above.. so with the help of the answers mentioned here and using hit and trial method, I found that when we press enter after giving input to any variable using scanf(), \n is stored in the next gets() function.. and next time it doesn't take any input from the keyboard.. so to avoid this just use getchar() in between the scanf() nd gets() nd also remember that getchar() takes only 1 character.. so don't give any extra input to scanf() as again this will be stored and will be used in gets() nd the problem will remain the same....
hope this will help..
thank u..

Related

C : when asking for 2 inputs from a user the 2nd question will not prompt an input to be stored in a variable

If I try grade or fullname one at a time I will get the expected result
"Enter your Grade: "
"Your grade is x"
"Enter your full name:"
"Your full name is xxxx xxxx"
If I run below the print out is
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
I can't figure out why I am not been prompted for a second input especially as I know it works when tried on its own */
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
scanf("%c"); buffer problem, %c will only eat one character, so or \n will stay in the buffer for the next one to read.
Try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
getchar(); // here
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
use getchar(); to eat the extra character in the buffer.
Don't mix scanf() with fgets() - in this case, the newline present in the buffer, left untouched by scanf() will be fed to fget() and it won't "ask" for any new input.
Better to use fgets() in all the user-inputs.
The problem lies in this line scanf("%c", &grade); Whenever you use scanf() always keep in mind that the enter key will be stored in your buffer. Since enter key was in your buffer, it went right into fullName when fgets(fullName, 20, stdin); is executed. That's way you got your output:
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
You can solve the problem by using getchar(); or getch(); right after scanf(); to capture the Enter key and ensures that fullName get the correct input. Another way to solve it is to use fflush(stdin);. They basically do the same thing, but fflush(stdin); clear Enter key from the buffer. Therefore, fflush(stdin); should be used after scanf(); to clear the unwanted Enter key left by scanf();
This is a long one and have a lot to take in, but I hope this information helps :)))

c program is bypassing gets()

#include<stdio.h>
int main()
{
int N,i,j,n,*numArray,count=0;
char **arr,*part1,*part2,*token;
scanf("%d",&N);
arr=(char **)malloc(N*sizeof(char *));
numArray=(int *)malloc(N*sizeof(int));
for(i=0;i<N;i++){
arr[i]=(char *)malloc(50*sizeof(char));
}
for(i=0;i<N;i++){
printf("plz enter %d th :",i);
gets(&arr[i][0]);// why is it not executing
}
for(i=0;i<N;i++){
printf("%s",arr[i]);
}
return 0;
}
I tried executing this code and found that the line gets(&arr[i][0]); does not get executed, i.e. it doesn't wait for user to input. Instead, it prints "plz enter 0 th: plz enter 1 th: plz enter 2 th: and so on" and doesn't wait for user to enter the string.
I am unable to get what exactly is wrong and what exactly is happening? Plese help. Thanks in advance.
This line inputing the number of entries
scanf("%d",&N);
leaves a newline in the input buffer. Then this line
gets(&arr[i][0]);
takes that lone newline as the first entry.
You can get rid of it like this
scanf("%d%*c",&N);
But you should not be using gets in this day and age, it is obsolete. This would have been better for the string entries (instead of the above mod)
scanf("%50s", arr[i]);
as well as checking the return value from all the scanf calls. The code still needs improvemnt though, since as stated scanf will only scan up to the first whitespace.
. it doesn't wait for user to input. Instead, it prints "plz enter 0
th: plz enter 1 th: plz enter 2 th: and so on"
this is due to problem of white space in your loop... instead try consuming them before every time you scan string using scanf(" ");, like this :
for(i=0;i<N;i++){
printf("plz enter %d th :",i);
scanf(" "); //to consume white spaces
gets(arr[i]);// why is it not executing? because of wrong arguments
}
EDIT : as suggested by #user3629249
Never use gets() for two major reasons:
It allows the input to overflow the input buffer
It is removed from the language from C11 onward.
a better alternative would be fgets()
and here's a link to know about it more: here

Simple C code not working

I have written a simple code to check whether a given character is present in the string entered by the user but it doesn't seem to work.
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],b;
int i,p=0,n;
printf("Enter the string-");
scanf("%s",a);
printf("\nEnter the character-");
scanf("%c",&b);
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
printf("\ncharacter is present in string\n");
p=1;
break;
}
}
if(p==0)
printf("\nchracter is not present in string\n");
return 0;
}
The output I get is this: http://i58.tinypic.com/2gvnedt.png
I do not see what is wrong with the code. If I replace "scanf("%s",a);" with "gets(a);" it works fine. Why?
Help is appreciated. Thanks!
Add a space character in:
scanf(" %c",&b);
^
To consume the trailing \n character that is left in stdin after the first scanf.
So a \n is left in the standard input from which scanf is reading. So when a new scanf is met it scans the old \n character.
To neutralize that effect I put a space character in scanf i.e. I am telling it to expect to read a \n or space or \t and then to read a %c.

Dev-C++ Input skipped

#include<stdio.h>
#include<conio.h>
main()
{
int i;
char c, text[30];
float f;
printf("\nEnter Integer : ");
scanf("%d",&i);
printf("\nEnter Character : ");
c = getch();
printf("\nEnter String:");
gets(text);
printf("\nEnter Float:");
scanf("%f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c8",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getch();
}
Why is this simple program not able to read a string using the gets() function? What else should I use to correct it? Well it it worked in Turbo C in my old 32-bit PC but not here...
Scanf or other input parsing functions take only required quantity of characters as specified in the call from stdin and reject others.As a result these rejected values,during next read of stdin enter into the variables along with the newline characters and thus skipping inputs for a few calls.So its better to call a clear routine that cleans stdin and stops garbage entering into other variables.
Although your code is quite vulnerable still it has solution:-
#include<stdio.h>
int clear()
{
while ((getchar())^'\n');
}
int main()
{
int i;
char c, text[30]={0};
float f;
printf("\nEnter Integer : ");
scanf(" %d",&i);
printf("\nEnter Character : ");
scanf(" %c",&c);
printf("\nEnter String:");
clear();
gets(text);
printf("\nEnter Float:");
scanf(" %f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getchar();
}
With some little research, I guess that the problem comes with scanf(). scanf() reads a line without the end of line character '\n' which seems to stay in the buffer and actually red by the next statement.
alternatively you can use fgets() and sscanf() as follows:
To read a character I used:
fgets(text,sizeof(text),stdin);
sscanf(text,"%c",&c); /* or: c = text[0]; */
to read an integer I have used
fgets(text,sizeof(text),stdin);
sscanf(text,"%d",&i);
I had a major problem with gets() in a C course I had (to which DevC++) was advised as a compiler. However, I totally recall I didn't follow the advice and it turned out that the behavior of fgets() is also compiler dependent.
The man page for gets() has this:
BUGS
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
When you type 42 (or whatever) as the first integer, you actually type three characters: 4, 2 and then the newline character that comes from pressing ENTER. Your first scanf reads an integer, which means that it only reads the 4 and the 2, leaving the newline character in the input buffer.
When your program gets to gets, it reads a the very short line that consists just of that newline character.
You can fix it by reading and throwing away the newline character just after scanf, something like this:
printf("\nEnter Integer : ");
scanf("%d",&i);
while (getchar() != '\n')
;

scanf gets the input of the previously excecuted getchar()

I am using getchar() in order to read characters and put them on a table, as well as scanf in order to get an integer.
The problem with the scanf() is that it doesn't wait for the users' input but reads from the buffer the last character given on the previous line, with getchar().
I tried sscanf, fflush(stdin); etc but I'm getting still the same behavior.
#include <stdio.h>
#include <stdlib.h>
main()
{
int i, choice, tmp_day, tmp_month;
char name[5];
printf("insert choice(1-3):\n");
scanf("%d",&choice);
printf("name: ");
for (i=0;i<5;i++) name[i]=getchar();
name[5] = '\0' ;
printf("day (1-31): ");
scanf("%d",&tmp_day);
printf("month (1-12): ");
scanf("%d",&tmp_month);
printf("\n%d %d", tmp_day, tmp_month);
}
Any idea?
Thanks in advance.
Detailed discussion about fflush(stdin) which not necessarily portable.
http://c-faq.com/stdio/gets_flush2.html
After each scanf use this statement:
fflush(stdin);

Resources