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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Sampad Saha
  • 59
  • 2
  • 5

1 Answers1

4

The problem here is, for an input like

abc XYZ

the code

  scanf("%s",name);

reads only the "abc" part and the "XYZ" is left in the input buffer. The later gets() read that, and puts() prints that. As you don't have a newline after the printf(), the output is not flushed and the outcome of the puts() 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 by scanf() ("abc")is not printed.

To elaborate, %s with scanf() cannot read whitespace delimited inputs, it stops the reading at the first whitespace encountered.

Quoting C11. chapter §7.21.6.2

s     Matches a sequence of non-white-space characters. [...]

which 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 the printf() and puts() outputs the same.

That said, DO NOT use gets(), it is dangerous. use fgets() instead.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I dont know if I am wrong or right..but isn't the print omition case (2nd example) printing the Saha only because same variable is being used in that case? And in first case it is stored in output buffer before it gets lost by reading from` gets()` Third case is obvious.. – user2736738 Dec 29 '16 at 16:49
  • @coderredoc Right, as long as the `pf/sf` and `gets/puts` pair uses the same variable, it will be the same. the variable _between_ the pair may change but not the result. :) – Sourav Ghosh Dec 29 '16 at 16:57