How do the puts and gets functions work?

末鹿安然 提交于 2019-11-27 09:38:32
Sourav Ghosh

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!