gets() not working as expected - c

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.

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.

What's the output of following program which shows the unusual output and why?

see the ouput image
What's the output of following code and why?
I am curious to know why c compiler shows the unusual output.
What happens behind the scene?
#include<stdio.h>
int main()
{
char a,b,c;
printf("Enter First char:");
scanf("%c",&a);
printf("Enter Second char:");
scanf("%c",&b);
printf("Enter Third char:");
scanf("%c",&c);
return 1;
}
Enter First char:a
Enter Second char:Enter Third char:c
see above output, its not taking 2nd input and directly asking third one!
First time you type 1 and hit Enter (Enter is interpreted as newline character)
The first scanf reads '1'.
The second scanf reads '\n'.
Then you type 2 and click Enter. The third scanf reads '2'.
Probably you need to read "%c " or " %c", since ' ' in format string skips all whitespaces.

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?

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

Second scanf is not working

i am having trouble with this c language code:
char st[2];
printf("enter first value:");
scanf("%c", &st[0]);
printf("enter second value:");
scanf("%c", &st[1]);
So my computer didn't ask me to enter the second value, I mean to say that it only print the first printf statement then I enter a character and then it only prints the second printf statement and program end without taking the second input.
Please help. What's wrong with this code?
-Thanks in advance.
Well it did. The character(s) produced by the ENTER key is present in the buffer already.
use fflush(stdin); function before the second scanf();. It will flush the ENTER key generated after first scanf();.
Actually, your second scanf() is taking the ENTER as its input and since scanf terminates after getting an ENTER, it is not taking anything else by your side.
I think your problem is the second scanf is receiving the "Enter" key press.
You're getting the implicit newline you entered as the second character, i.e. st[1] is getting the value '\n'. An easy way to fix this is to include the newline in the expected format string: scanf("%c\n", &st[0]);
Change
scanf("%c", &st[0]);
to this
scanf(" %c", &st[0]);
That's a shotty answer (no error checking or anything) but its quick and easy.

Resources