Input reading using scanf hangs - c

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?

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.

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

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?

how many times this loop will be executed?

I write this code, which takes an integer number (t) as input from the user. A loop will be executed just 't' times. But I find that it runs for (t-1) times. For example, if I give input 3, it runs only 2 times. Can anyone please explain why this is happening?
I tried and used scanf("%s", &str), it works, but then I can't take a string as input that contains spaces.
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
char str[100];
gets(str);
printf("%s\n", str);
}
return 0;
}
scanf("%d", &t) consumes only the numeral in the input stream and leaves the remaining characters. When you enter a numeral and press enter, there is a newline character after the numeral.
The first gets reads this newline and returns a string that is empty except for the newline. The first iteration of the loop prints this blank line.
Loop is iterating 3 times as it should.But it seems that it is iterating 2 times only because of the reason that the \n character left behind by gets in the buffer is read in second iteration.
For first iteration, when you enter a string and the press Enter, the \n character go to the buffer with the string. gets stop reading when it encounters \0, leaving \n in the buffer. On next iteration this \n (non printable character) is read by gets and then printed to terminal.
NOTE: Never use gets function. It is no longer is the part of standard C. Use fgets instead.
I guess you can also use the scanf function to resolve your problem that the string is not accepting anything after a SPACE . Also, the loop is running (t-1) times because the buffer is not being cleared due to the use of gets() . In order to resolve this, you can use the getch() function to clear the buffer. The following code should work I guess,
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
char str[100];
scanf("%[^\n]c",&str);
printf("%s\n", str);
getch();
}
return 0;
}
In this code, the getch() will clear the buffer by accepting the useless value. Also as far as scanf() is considered, the ^ inside the scanf tells the function that it needs to take the input till the character after the ^ is encountered which in this case is an escape sequence of NEW LINE . I have tried using some small words as well instead of the newline and it has worked as well. Hope this clears your issue :)

can any one explain the output of this program?

Why does following program produce two output message at the same time, without asking for any input from the user???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
The output is followings:
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Terminal input is read line at a time unless you specify otherwise; scanf reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf() or similar to parse those lines.
Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?

Resources