gpt4 book ai didi

c、gets()、fgets()

转载 作者:行者123 更新时间:2023-12-02 08:56:00 25 4
gpt4 key购买 nike

char s1[100];
char s2[100];
gets(s1);
fgets(s2,sizeof(s2),stdin);
printf("%d,%d\n",strlen(s1),strlen(s2));

运行后,我输入了两次“abcd”,我得到的结果是:4,5这是为什么?

最佳答案

来自 gets/fgets 手册页:

 The fgets() function reads at most one less than the number of characters
specified by n from the given stream and stores them in the string s.
Reading stops when a newline character is found, at end-of-file or error.
The newline, if any, is retained. If any characters are read and there
is no error, a `\0' character is appended to end the string.

The gets() function is equivalent to fgets() with an infinite n and a
stream of stdin, except that the newline character (if any) is not stored
in the string. It is the caller's responsibility to ensure that the
input line, if any, is sufficiently short to fit in the string.

fgets 保留换行符,即第 5 个字符,但 gets 不保留。此外,请养成始终使用 fgets 的习惯,因为在使用 gets 时无法防止缓冲区溢出。

关于c、gets()、fgets(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4810764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com