c program is bypassing gets() - c

#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

Related

What is wrong with my for loop? It turns 2 times when I enter only 1 input in a letter guessing game in C

I know this code is not completed yet, but I cannot go any further because of this issue.
If you execute the code with any compiler you will see it.
After the instructions gets written at console, when you enter a word, loop takes 2 turns. It reduces chance 2 times too when it's supposed to be 1. Why is that?
I am using devc++ and windows.
#include<stdio.h>
#include<stdlib.h>
int main(){
int i,j,totalTrial=6,currentTrial=0;
char myWord [6]={'d','o','c','t','o','r'};
char lineArray [6]={'-','-','-','-','-','-'};
char guess;
printf("Hello,this is a simple word-guessing game. Try to find my secret word. You have 6 chances.");
printf("Lets begin!!\n");
printf("Word:\n------\n");
for(i=0;i<=6;i++)
{
printf("\nGuess a letter: ");
scanf("%c",&guess);
for(j=0;j<7;j++)
{
if(guess==myWord[j])
{
lineArray[j]=guess;
}
}
currentTrial++;
printf("\nResult: %s, %d hakkin kaldi.\n",lineArray,totalTrial-currentTrial);
}
getch();
return 0;
}
This is happening because the scanf() is reading the stray \n (newline character) from the input buffer. [When you are giving input, you must be entering a character followed by ENTER key.]
To resolve this, add a space before % character in scanf() like this:
scanf(" %c", &guess);
This will skip the leading whitespace characters (including newline character) and read the input given by the user.
With regard to the line:
scanf("%c",&guess);
How many characters do you think are turning up when you enter, for example, dENTER? I'll give you a hint, it isn't one :-)
The problem is that your scanf will read each character in turn and process it, including the newline generated when you hit ENTER.
A better solution would be to use a more complete input solution such as this one here.
It will handle many scenarios that a simple method based on scanf or getchar.

Input reading using scanf hangs

I am programming in C and i have a problem when i run a program in the cmd terminal. here is the code i use:
#include <stdio.h>
int main() {
int num;
printf("enter a number: ");
scanf("%i\n", &num);
for(int n = 1; n < num + 1; n++){
printf("%i\n", n);
}
return 0;
}
Generally, everything works like it should, exept for one thing.
when I enter a number, nothing happens. there is no output, until I write anything and press Enter, and only then the number appear.
this is a screenshot of what it looks like.
here is enter the number (and press enter) but nothing happens: http://prntscr.com/deum9a
and this is how it looks like after i entered something random nad all the numbers popped up: http://prntscr.com/deumyn
if anyone knows how to fix this, please tell me (:
Remove the \n from scanf()
scanf("%i", &num);
When you have a whitespace character in the format string, scanf() will ignore any number of whtiespaces you input and thus the ENTER you do doesn't terminate the input reading. Basically, you'll be forced to input a non whitespace character again in order complete the scanf() call.
Generally, scanf() is considered bad for input reading. So, considering using fgets() and parsing the input using sscanf().
See: Why does everyone say not to use scanf? What should I use instead?

gets() not working as expected

So first of all I would like to paste my code in here for future references:
int dayNum = 0;
printf("\n\nEnter your date(1 - 30/31): ");
scanf("%d\n", &dayNum);
printf("\n\nEnter your note:");
char note[10000];
gets(note);
printf("%s", note);
The code is I think self-explanatory and easy-to-understand. However, here is a quick and short explanation from my side. This code just gets an integer input and stores it into a variable and then gets ready to take a string as an input and print it out to the console.
What I expect:
I expect the code to run like this:
Enter your date(1 - 30/31): <my_input>
Enter your note: <my_long_note>
<my_long_note> //prints my note that I wrote above
What is happening:
But, what is happening right now is like this(abnormal):
Enter your date(1 - 30/31): <my_input>
<my_long_note> //this is an input
Enter your note: <my_long_note> //this is an output
As you can see, it takes my note before printing out Enter your note:.
Can someone tell me why is that happening? I am not quite sure of what did I do wrong in there.
You need to flush your output stream.. That means including a \n in the printf, or by manually calling fflush(stdout).
Ah, so after another search, I found this:
Using scanf("%d%*c", &a). The %*c term causes scanf to read in one character (the newline) but the asterisk causes the value to be discarded.
So my final code became this:
int dayNum = 0;
printf("\n\nEnter your date(1 - 30/31): ");
scanf("%d%*c", &dayNum);
printf("\n\nEnter your note:");
char note[10000];
gets(note);
printf("%s", note);
And, it worked.

why does my int while loop keeps going when i scan for a number?

I'm having a problem with a while loop. I have to enter a number which is bigger than 0 and below 81. when I use numbers like -1,0,1,2,82 it is going good and I get the expected result, but when I use a letter it keeps going through my while loop. I've used the debugger in eclipse and when I'm at the while loop amount is automatically set to '0' because of the failed scanf. Why does it keep looping when I insert a letter?
#include <stdio.h>
#include <stdlib.h>
int main(){
int amount = 0;
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
while(amount <= 0 || amount >= 81){
printf("Wrong input try again.\n");
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
}
return EXIT_SUCCESS;
}
You need to make sure the scanf() worked. Use the returned value to do that
if (scanf("%d", &amount) != 1) /* error */;
When it doesn't work (because eg a letter was found in input) you probably want to get rid of the cause of the error.
A better option to get input from users is to use fgets()
See this related question: scanf() is not waiting for user input
The reason is that when you press enter with a char, scanf failed and didn't eat up the char in the input feed. As a result, the next block begins having whatever you entered before.
You can check that by adding a getchar() before the scanf() inside the while loop. You'll notice that it'll repeat the while loop as many times as your line has invalid characters, then stop and wait for input. The getchar() ate one of the invalid chars in the input each time the loop ran.
It would be better not to use scanf like that, though. Take a look a this resource:
Reading a line using scanf() not good?

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

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..

Resources