char s1[100];
char s2[100];
gets(s1);
fgets(s2,sizeof(s2),stdin);
printf("%d,%d\n",strlen(s1),strlen(s2));
运行后,我输入 “ABCD” 两次, ,结果我得到的是:4,5
这是为什么?C,获得()与fgets()
char s1[100];
char s2[100];
gets(s1);
fgets(s2,sizeof(s2),stdin);
printf("%d,%d\n",strlen(s1),strlen(s2));
运行后,我输入 “ABCD” 两次, ,结果我得到的是:4,5
这是为什么?C,获得()与fgets()
从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
时无法防止缓冲区溢出。
因为fgets
返回的字符串结尾为'\n'
而gets
不是。
其他方法,我想。 – 2011-01-26 22:30:56
你说得对。编辑。 – Marii 2011-01-26 22:32:50
的
gets()
函数等效于fgets()
具有无限n
和的stdin
stream
,不同之处在于换行字符(如果有的话)不存储在的字符串中。
从[a`gets`手册页](http://linux.die.net/man/3/gets):“千万不要使用gets()。因为事先不知道数据是不可能的许多字符gets()会被读取,并且由于gets()会继续存储缓冲区末尾的字符,因此使用它非常危险,已经被用于破坏计算机安全性,请使用fgets()。 – 2011-01-26 22:33:12