How do the puts and gets functions work?

后端 未结 1 1751
南笙
南笙 2020-12-02 01:24
main()
{
char name[20];

printf(\"enter your name\\n\");

scanf(\"%s\",name);       
printf(\"%s\",name);

gets(name);
puts(name);
}

相关标签:
1条回答
  • 2020-12-02 02:03

    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.

    0 讨论(0)
提交回复
热议问题