I have tried to use gets()
library function in C and found that printf()
statement output is delayed and got displayed after gets()
receiving the input from stdin (i.e. from keyboard). Please check below C code and its output.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i, j;
char ch, *str;
printf("Enter size of input:\n");
scanf("%d\n", &n);
str = (char *) malloc(sizeof(char) * n);
printf("Enter input string: \n");
gets(str);
printf("Given input string is : %s\n", str);
return 0;
}
Output:
Enter size of input: 9
R Raj Kumar <-- This name is given from input since program is waiting for input for gets() function even though printf("Enter input string\n") is present before gets() and printf() statement is not displayed on the console. It is getting printed after receiving gets() input from console.
Enter input string:
Given input string is : R Raj Kumar
gets
is deprecated for a reason. – Deduplicatorgets()
for the reasons described in the linked Q&A. – Jonathan Leffler'\n'
inscanf("%d\n", &n);
"delays".scanf("%d\n", &n)
does not return until non-white- space is entered after the number. @JonathanLeffler Disagree that the posted dupe is a good explanation of this - which is the first of many problems with this code. – chux - Reinstate Monica\n
in thescanf()
format"%d\n"
as chux said. Remove it. Then add a 'gobble' loop:int ch; while ((ch = getchar()) != EOF && ch != '\n') ;
(empty loop body). That reads the trailing newline. – Jonathan Leffler