How do the puts and gets functions work?

末鹿安然 提交于 2019-12-28 03:11:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41383492/how-do-the-puts-and-gets-functions-work

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