main()
{
char name[20];
printf("enter your name\n");
scanf("%s",name);
printf("%s",name);
gets(name);
puts(name);
}
input: Sampad Saha
Output
Sampad Saha
Here puts only uses the input taken from gets()
.
as, if I omit this printf()
the output would be
Saha
So here puts does not print anything given through scanf()
.
main()
{
char color[20];
printf("enter your name\n");
scanf("%s",color);
puts(color);
}
But here puts()
uses the input taken from scanf()
also.
The problem here is, for an input like
the code
reads only the "abc" part and the "XYZ" is left in the input buffer. The later
gets()
read that, andputs()
prints that. As you don't have anewline
after theprintf()
, the output is not flushed and the outcome of theputs()
is appended to the output stream buffer and once the program finishes execution, the whole output buffer is flushed altogether printing the whole input together.So, in the other case, when you drop the
printf()
, the value read byscanf()
("abc")is not printed.To elaborate,
%s
withscanf()
cannot read whitespace delimited inputs, it stops the reading at the first whitespace encountered.Quoting
C11
. chapter ยง7.21.6.2which indicates, for
%s
,scanf()
stops reading upon encountering first whitespace.Coming to the second case, where the input does not contain a whitespace, (i.e., not a whitespace-separated input is given),
scanf()
reads the whole input (upto terminating newline) and thus, both theprintf()
andputs()
outputs the same.That said, DO NOT use
gets()
, it is dangerous. usefgets()
instead.